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


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

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


当前回答

要插入深厚的数据结构,请使用 iteration_utilities.deepflatten1:

>>> from iteration_utilities import deepflatten

>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> list(deepflatten(l, depth=1))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> l = [[1, 2, 3], [4, [5, 6]], 7, [8, 9]]
>>> list(deepflatten(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

这是一个发电机,所以你需要将结果投到列表中,或者明确地对其进行调解。


要单一的平面,如果每一个项目本身是不可分割的,你也可以使用 iteration_utilities.flatten 它本身只是一个薄的旋转器周围 itertools.chain.from_iterable:

>>> from iteration_utilities import flatten
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> list(flatten(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

只需添加一些时间表(基于Nico Schlömer的答案,其中不包含此答案中的功能):

此分類上一篇

结果表明,如果 iterable 只包含几个内部 iterables 那么 总数将是最快的,但是,对于长期 iterables 只有 itertools.chain.from_iterable, iteration_utilities.deepflatten 或 nested 理解具有合理的性能, itertools.chain.from_iterable 是最快的(如 Nico Schlömer 已经注意到)。

from itertools import chain
from functools import reduce
from collections import Iterable  # or from collections.abc import Iterable
import operator
from iteration_utilities import deepflatten

def nested_list_comprehension(lsts):
    return [item for sublist in lsts for item in sublist]

def itertools_chain_from_iterable(lsts):
    return list(chain.from_iterable(lsts))

def pythons_sum(lsts):
    return sum(lsts, [])

def reduce_add(lsts):
    return reduce(lambda x, y: x + y, lsts)

def pylangs_flatten(lsts):
    return list(flatten(lsts))

def flatten(items):
    """Yield items from any nested iterable; see REF."""
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x

def reduce_concat(lsts):
    return reduce(operator.concat, lsts)

def iteration_utilities_deepflatten(lsts):
    return list(deepflatten(lsts, depth=1))


from simple_benchmark import benchmark

b = benchmark(
    [nested_list_comprehension, itertools_chain_from_iterable, pythons_sum, reduce_add,
     pylangs_flatten, reduce_concat, iteration_utilities_deepflatten],
    arguments={2**i: [[0]*5]*(2**i) for i in range(1, 13)},
    argument_name='number of inner lists'
)

b.plot()

1 Disclaimer:我是该图书馆的作者

其他回答

使用 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]
def flatten_array(arr):
  result = []
  for item in arr:
    if isinstance(item, list):
      for num in item:
        result.append(num)
    else:
      result.append(item)
  return result

print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
// output: [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]
np.hstack(listoflist).tolist()

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

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)]