2013-11-01 87 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

相關問題