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


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

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


当前回答

考虑安装 more_itertools 包。

> pip install more_itertools

它配备了一个应用程序为平板(来源,从 itertools 食谱):

import more_itertools


lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.flatten(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

注意:正如文件中提到的那样,平板需要列表。 查看下面的平板更多不规则输入。


至于版本 2.4,您可以用更多_itertools.collapse (来源,由abarnet 贡献) 插入更复杂、更精致的 iterables。

lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.collapse(lst)) 
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

lst = [[1, 2, 3], [[4, 5, 6]], [[[7]]], 8, 9]              # complex nesting
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

其他回答

作者的注意事项:这是非常不有效的,但有趣,因为单曲是惊人的。

>>> xss = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> sum(xss, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

总数是不可分割 xss 的元素,并使用第二个论点作为总数的初始值(默认初始值为0,这不是列表)。

因為你們是清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清。

请注意,它只适用于列表列表,对于列表列表列表,您将需要另一个解决方案。

根據您的列表(1, 2, 3), [4, 5, 6], [7], [8, 9] 是 1 列表水平,我們可以簡單地使用數量(列表),而不使用任何圖書館。

sum([[1, 2, 3], [4, 5, 6], [7], [8, 9]],[])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

延伸此方法的优势,当内部存在一个<unk>或数字时,简单地将每个元素的地图函数添加到列表中

#For only tuple
sum(list(map(list,[[1, 2, 3], (4, 5, 6), (7,), [8, 9]])),[])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

#In general

def convert(x):
    if type(x) is int or type(x) is float:
           return [x]
    else:
           return list(x)

sum(list(map(convert,[[1, 2, 3], (4, 5, 6), 7, [8, 9]])),[])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

在这里,有一个明确的解释的缺点在记忆的这个方法。 简而言之,它重复创建列表对象,应该避免( )

考虑安装 more_itertools 包。

> pip install more_itertools

它配备了一个应用程序为平板(来源,从 itertools 食谱):

import more_itertools


lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.flatten(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

注意:正如文件中提到的那样,平板需要列表。 查看下面的平板更多不规则输入。


至于版本 2.4,您可以用更多_itertools.collapse (来源,由abarnet 贡献) 插入更复杂、更精致的 iterables。

lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.collapse(lst)) 
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

lst = [[1, 2, 3], [[4, 5, 6]], [[[7]]], 8, 9]              # complex nesting
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

如果你有一个Numpy Array A:

a = np.array([[1,2], [3,4]])
a.flatten('C')

生产:

[1, 2, 3, 4]

np.flatten 也接受其他参数:

C: F A K

有关参数的详细信息可在这里找到。

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

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)