2013-11-01 46 views
0

我有一个列表,其中包含几个子列表,每个子列表中都有一个给定数量的元素。我需要将所有子列表中的所有元素移动到另一个列表中,即:消除子列表中元素间的分离。将元素从列表中移出到新列表中

这是什么,如果我的意思是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做到这一点。

+0

看到这里http://stackoverflow.com/questions/952914/making-a -flat-list-of-list-of-lists-in-python – jaap

回答

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

2

试试这个:

[item for sublist in a for item in sublist] 
+0

这工作完美b我标记了另一个被接受的答案,因为正如作者所说,答案要快得多。非常感谢你! – Gabriel

相关问题