将元素从子列表中移出到新列表中

时间:2013-11-01 17:28:37

标签: python list

我有一个列表,其中包含多个子列表,每个子列表中都包含一定数量的元素。我需要将所有子列表中的所有元素移动到另一个列表中,即:删除子列表强加的元素之间的分隔。

如果我的意思是这是一个MWE:

a = [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], [[17, 18, 19, 20], [21, 22, 23, 24]], [[25, 26, 27, 28], [26, 30, 31, 32], [33, 34, 35, 36]]]

b = []
    for elem in a:
        for item in elem:
            b.append(item)

导致:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [26, 30, 31, 32], [33, 34, 35, 36]]

我确信在python中有更优雅,更简单的方法。

2 个答案:

答案 0 :(得分:2)

使用itertools.chain.from_iterable

>>> from itertools import chain
>>> list(chain.from_iterable(a))
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [26, 30, 31, 32], [33, 34, 35, 36]]

Timing comparison:

enter image description here

答案 1 :(得分:2)

试试这个:

[item for sublist in a for item in sublist]