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


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

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


当前回答

如果我想添加一些东西到以前的答案,这里是我的重复滑板功能,可以滑板不只是滑板列表,但也任何提供的容器或一般任何物品,可以扔出物品。

def flatten(iterable):
    # These types won't considered a sequence or generally a container
    exclude = str, bytes

    for i in iterable:
        try:
            if isinstance(i, exclude):
                raise TypeError
            iter(i)
        except TypeError:
            yield i
        else:
            yield from flatten(i)

这样,你可以排除你不想要的类型,如 str 或其他。

想法是,如果一个对象可以通过 iter(),它已经准备好产生物品,所以 iterable 甚至可以作为一个对象具有发明器表达式。

有人可以争论:为什么你写了这么一般的,当OP没有要求它?OK,你是对的,我只是觉得这可能帮助某人(就像它为我做的那样)。

测试案例:

lst1 = [1, {3}, (1, 6), [[3, 8]], [[[5]]], 9, ((((2,),),),)]
lst2 = ['3', B'A', [[[(i ** 2 for i in range(3))]]], range(3)]

print(list(flatten(lst1)))
print(list(flatten(lst2)))

出口:

[1, 3, 1, 6, 3, 8, 5, 9, 2]
['3', b'A', 0, 1, 4, 0, 1, 2]

其他回答

我想要一個解決方案,可以處理多種<unk>(<unk>,<unk>,<unk>,<unk>),<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>。

这就是我所带来的:

def _flatten(l) -> Iterator[Any]:
    stack = l.copy()
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            stack.extend(item)
        else:
            yield item


def flatten(l) -> Iterator[Any]:
    return reversed(list(_flatten(l)))

和测试:

@pytest.mark.parametrize('input_list, expected_output', [
    ([1, 2, 3], [1, 2, 3]),
    ([[1], 2, 3], [1, 2, 3]),
    ([[1], [2], 3], [1, 2, 3]),
    ([[1], [2], [3]], [1, 2, 3]),
    ([[1], [[2]], [3]], [1, 2, 3]),
    ([[1], [[[2]], [3]]], [1, 2, 3]),
])
def test_flatten(input_list, expected_output):
    assert list(flatten(input_list)) == expected_output

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

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

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

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

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

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

考虑到列表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 列表时 - 因为中间结果列表保持长,每个步骤都会分配一个新的中间结果列表对象,前中间结果中的所有对象都必须复制(以及在结尾添加一些新的对象)。

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

考虑到列表只有整体:

import re
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(map(int,re.sub('(\[|\])','',str(l)).split(',')))