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


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

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


当前回答

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

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

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

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

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

其他回答

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

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',
    )

出口:

此分類上一篇

使用 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]

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

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)

我创建了一点功能,基本上可以平滑任何东西. 你可以用管道:管道安装平滑一切

from flatten_everything import flatten_everything
withoutprotection=list(
    flatten_everything(
        [
            1,
            1,
            2,
            [3, 4, 5, [6, 3, [2, 5, ["sfs", "sdfsfdsf",]]]],
            1,
            3,
            34,
            [
                55,
                {"brand": "Ford", "model": "Mustang", "year": 1964, "yearxx": 2020},
                pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}),
                {"col1": [1, 2], "col2": [3, 4]},
                55,
                {"k32", 34},
                np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
                (np.arange(22), np.eye(2, 2), 33),
            ],
        ]
    )
)
print(withoutprotection)
output:
[1, 1, 2, 3, 4, 5, 6, 3, 2, 5, 'sfs', 'sdfsfdsf', 1, 3, 34, 55, 'Ford', 'Mustang', 1964, 2020, 1, 2, 3, 4, 1, 2, 3, 4, 55, 34, 'k32', 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 1.0, 0.0, 0.0, 1.0, 33]

你甚至可以保护物体免受闪烁:

from flatten_everything import ProtectedDict,ProtectedList,ProtectedTuple
withprotection=list(
    flatten_everything(
        [
            1,
            1,
            2,
            [3, 4, 5, [6, 3, [2, 5, ProtectedList(["sfs", "sdfsfdsf",])]]],
            1,
            3,
            34,
            [
                55,
                ProtectedDict({"brand": "Ford", "model": "Mustang", "year": 1964, "yearxx": 2020}),
                pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}),
                {"col1": [1, 2], "col2": [3, 4]},
                55,
                {"k32", 34},
                np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
                ProtectedTuple((np.arange(22), np.eye(2, 2), 33)),
            ],
        ]
    )
)
print(withprotection)
output:
[1, 1, 2, 3, 4, 5, 6, 3, 2, 5, ['sfs', 'sdfsfdsf'], 1, 3, 34, 55, {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'yearxx': 2020}, 1, 2, 3, 4, 1, 2, 3, 4, 55, 34, 'k32', 1, 2, 3, 4, 5, 6, 7, 8, (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,17, 18, 19, 20, 21]), array([[1., 0.], [0., 1.]]), 33)]

您也可以使用NumPy的公寓:

import numpy as np
list(np.array(l).flat)

它只有在超级列表具有相同的尺寸时才有效。