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


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

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


当前回答

最简单的方式在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]

其他回答

matplotlib.cbook.flatten() 将为粘贴列表工作,即使它们比示例更深地粘贴。

import matplotlib
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
print(list(matplotlib.cbook.flatten(l)))
l2 = [[1, 2, 3], [4, 5, 6], [7], [8, [9, 10, [11, 12, [13]]]]]
print(list(matplotlib.cbook.flatten(l2)))

结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

这比 underscore 快 18 倍。

Average time over 1000 trials of matplotlib.cbook.flatten: 2.55e-05 sec
Average time over 1000 trials of underscore._.flatten: 4.63e-04 sec
(time for underscore._)/(time for matplotlib.cbook) = 18.1233394636

我想要一個解決方案,可以處理多種<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

最简单的方式在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]

如果你有一个Numpy Array A:

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

生产:

[1, 2, 3, 4]

np.flatten 也接受其他参数:

C: F A K

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

您可以使用 itertools.chain():

>>> import itertools
>>> list2d = [[1,2,3], [4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain(*list2d))

或者您可以使用 itertools.chain.from_iterable(),不需要与 * 运营商解包列表:

>>> import itertools
>>> list2d = [[1,2,3], [4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain.from_iterable(list2d))

这种方法可能比 [分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类

$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))'
20000 loops, best of 5: 10.8 usec per loop
$ python3 -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 5: 21.7 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 5: 258 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;from functools import reduce' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 5: 292 usec per loop
$ python3 --version
Python 3.7.5rc1