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


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

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


当前回答

考虑到列表L的列表,

flat_list = [item for sublist in l for item in sublist]

意思是:

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

它比迄今为止发布的短篇文章更快(l 是表格的列表)。

下面是相应的功能:

def flatten(l):
    return [item for sublist in l for item in sublist]

作为证据,您可以在标准图书馆中使用时间模块:

$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 1.1 msec per loop

解释:基于 + 的缩写(包括在总中使用)是必然的 O(L**2)当有 L 列表时 - 因为中间结果列表保持长,每个步骤都会分配一个新的中间结果列表对象,前中间结果中的所有对象都必须复制(以及在结尾添加一些新的对象)。

列表理解只产生一个列表,一次,并复制每个项目(从其原始居住地到结果列表)也准确一次。

其他回答

np.hstack(listoflist).tolist()

考虑到列表L的列表,

flat_list = [item for sublist in l for item in sublist]

意思是:

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

它比迄今为止发布的短篇文章更快(l 是表格的列表)。

下面是相应的功能:

def flatten(l):
    return [item for sublist in l for item in sublist]

作为证据,您可以在标准图书馆中使用时间模块:

$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 1.1 msec per loop

解释:基于 + 的缩写(包括在总中使用)是必然的 O(L**2)当有 L 列表时 - 因为中间结果列表保持长,每个步骤都会分配一个新的中间结果列表对象,前中间结果中的所有对象都必须复制(以及在结尾添加一些新的对象)。

列表理解只产生一个列表,一次,并复制每个项目(从其原始居住地到结果列表)也准确一次。

使用 functools.reduce,将积累的列表 xs 添加到下列列表 ys:

from functools import reduce
xss = [[1,2,3], [4,5,6], [7], [8,9]]
out = reduce(lambda xs, ys: xs + ys, xss)

出口:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

使用 operator.concat 的更快方法:

from functools import reduce
import operator
xss = [[1,2,3], [4,5,6], [7], [8,9]]
out = reduce(operator.concat, xss)

出口:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

最简单的方式在Python没有任何图书馆

此功能还将适用于多维列表。

使用 recursion 我们可以实现列表中的任何组合,我们可以无需使用任何图书馆。

#Devil
x = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]


output = []
def flatten(v):
    if isinstance(v, int):
        output.append(v)
    if isinstance(v, list):
        for i in range(0, len(v)):
            flatten(v[i])

flatten(x)
print("Output:", output)
#Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

#Adding more dimensions 
x = [ [1, [2, 3, [4, 5], [6]], 7 ], [8, [9, [10]]] ]
flatten(x)
print("Output:", output)
#Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

这对我来说似乎是最简单的:

>>> import numpy as np
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> print(np.concatenate(l))
[1 2 3 4 5 6 7 8 9]