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


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

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


当前回答

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

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

出口:

此分類上一篇

其他回答

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

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)

如果你想清理一切,并保持一个单独的元素列表,你也可以使用它。

list_of_lists = [[1,2], [2,3], [3,4]]
list(set.union(*[set(s) for s in list_of_lists]))

def flatten(itr):
    for x in itr:
        try:
            yield from flatten(x)
        except TypeError:
            yield x

使用:这是一个发电机,通常你想将它插入一个不可分割的构建器,如列表()或<<<<<<<<或使用它在一个为旋转。

这个解决方案的好处是:

工作任何类型的无缝(即使是未来的!)工作任何组合和深度的无缝工作,如果顶级包含无依赖物品,快速和高效(你可以平滑无缝的部分,没有浪费时间的剩余部分你不需要)多样性(你可以使用它来构建一个无缝的你的选择或在旋转)

注:由于所有 iterables 都是浮动的,所以线条分为单个字符的序列. 如果您不喜欢/不喜欢这种行为,您可以使用下列版本,从浮动的 iterables 如线条和比特中进行过滤:

def flatten(itr):
    if type(itr) in (str,bytes):
        yield itr
    else:
        for x in itr:
            try:
                yield from flatten(x)
            except TypeError:
                yield x

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