以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。


如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?

在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。


当前回答

如果你愿意放弃一小量的速度,以便更清洁的外观,那么你可以使用numpy.concatenate().tolist() 或 numpy.concatenate().ravel().tolist():

import numpy

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] * 99

%timeit numpy.concatenate(l).ravel().tolist()
1000 loops, best of 3: 313 µs per loop

%timeit numpy.concatenate(l).tolist()
1000 loops, best of 3: 312 µs per loop

%timeit [item for sublist in l for item in sublist]
1000 loops, best of 3: 31.5 µs per loop

您可以在文档中了解更多, numpy.concatenate 和 numpy.ravel。

其他回答

我用 perfplot 测试了大多数建议的解决方案(我的宠物项目,基本上是时间周围的插槽),并发现

import functools
import operator
functools.reduce(operator.iconcat, a, [])

要成为最快的解决方案,无论是许多小列表还是很少的长列表都被混合(operator.iadd 同样快)。

更简单、更可接受的选择是

out = []
for sublist in a:
    out.extend(sublist)

如果字体列表的数量很大,这表现得比上面的建议略糟糕。

此分類上一篇

此分類上一篇


重复字符的代码:

import functools
import itertools
import operator

import numpy as np
import perfplot


def forfor(a):
    return [item for sublist in a for item in sublist]


def sum_brackets(a):
    return sum(a, [])


def functools_reduce(a):
    return functools.reduce(operator.concat, a)


def functools_reduce_iconcat(a):
    return functools.reduce(operator.iconcat, a, [])


def itertools_chain(a):
    return list(itertools.chain.from_iterable(a))


def numpy_flat(a):
    return list(np.array(a).flat)


def numpy_concatenate(a):
    return list(np.concatenate(a))


def extend(a):
    out = []
    for sublist in a:
        out.extend(sublist)
    return out


b = perfplot.bench(
    setup=lambda n: [list(range(10))] * n,
    # setup=lambda n: [list(range(n))] * 10,
    kernels=[
        forfor,
        sum_brackets,
        functools_reduce,
        functools_reduce_iconcat,
        itertools_chain,
        numpy_flat,
        numpy_concatenate,
        extend,
    ],
    n_range=[2 ** k for k in range(16)],
    xlabel="num lists (of length 10)",
    # xlabel="len lists (10 lists total)"
)
b.save("out.png")
b.show()

你可以使用列表扩展方法. 它显示是最快的:

flat_list = []
for sublist in l:
    flat_list.extend(sublist)

表演:

import functools
import itertools
import numpy
import operator
import perfplot


def functools_reduce_iconcat(a):
    return functools.reduce(operator.iconcat, a, [])


def itertools_chain(a):
    return list(itertools.chain.from_iterable(a))


def numpy_flat(a):
    return list(numpy.array(a).flat)


def extend(a):
    n = []

    list(map(n.extend, a))

    return n


perfplot.show(
    setup = lambda n: [list(range(10))] * n,
    kernels = [
        functools_reduce_iconcat, extend, itertools_chain, numpy_flat
        ],
    n_range = [2**k for k in range(16)],
    xlabel = 'num lists',
    )

出口:

此分類上一篇

对于包含多个列表的列表,这里是一个重复的解决方案,为我工作,我希望它是正确的:

# Question 4
def flatten(input_ls=[]) -> []:
    res_ls = []
    res_ls = flatten_recursive(input_ls, res_ls)

    print("Final flatten list solution is: \n", res_ls)

    return res_ls


def flatten_recursive(input_ls=[], res_ls=[]) -> []:
    tmp_ls = []

    for i in input_ls:
        if isinstance(i, int):
            res_ls.append(i)
        else:
            tmp_ls = i
            tmp_ls.append(flatten_recursive(i, res_ls))

    print(res_ls)
    return res_ls


flatten([0, 1, [2, 3], 4, [5, 6]])  # test
flatten([0, [[[1]]], [[2, 3], [4, [[5, 6]]]]])

出口:

[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
Final flatten list solution is: 
 [0, 1, 2, 3, 4, 5, 6]
[0, 1]
[0, 1]
[0, 1]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
Final flatten list solution is: 
 [0, 1, 2, 3, 4, 5, 6]

我会建议使用发电机与产量声明和产量从。

from collections.abc import Iterable

def flatten(items, ignore_types=(bytes, str)):
    """
       Flatten all of the nested lists to the one. Ignoring flatting of iterable types str and bytes by default.
    """
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, ignore_types):
            yield from flatten(x)
        else:
            yield x

values = [7, [4, 3, 5, [7, 3], (3, 4), ('A', {'B', 'C'})]]

for v in flatten(values):
    print(v)
np.hstack(listoflist).tolist()