2012-01-08 15 views
7

爲什麼使用擴展當你只能使用+ =運算符?哪種方法最好? 還什麼是連接多個列出一個列表中的最佳方式爲什麼要擴展一個python列表

#my prefered way 
_list=[1,2,3] 
_list+=[4,5,6] 
print _list 
#[1, 2, 3, 4, 5, 6] 

#why use extend: 
_list=[1,2,3] 
_list.extend([4,5,6]) 
print _list 
#[1, 2, 3, 4, 5, 6] 



_lists=[range(3*i,3*i+3) for i in range(3)] 
#[[0, 1, 2], [3, 4, 5], [6, 7, 8]] 

#my prefered way of merging lists 
print sum(_lists,[]) 
#[0, 1, 2, 3, 4, 5, 6, 7, 8] 


#is there a better way? 
from itertools import chain 
print list(chain(*_lists)) 
#[0, 1, 2, 3, 4, 5, 6, 7, 8] 

回答

16

+=只能使用延長一個列表中的另一列表,而extend可以使用一個迭代的對象擴展一個列表

eg

你可以做

a = [1,2,3] 
a.extend(set([4,5,6])) 

,但你不能做

a = [1,2,3] 
a += set([4,5,6]) 

對於第二個問題

[item for sublist in l for item in sublist] is faster. 

看到Making a flat list out of list of lists in Python

+0

謝謝!這很適合它。 _list + = list(_iterable)是否相等? – 2012-01-08 05:27:53

+1

可以實現相同的結果,但底層的實現會有所不同。 – qiao 2012-01-08 05:32:34

1

您可能extend()一個pytho列表中有一個非列表對象作爲迭代器。迭代器不存儲任何值,而是一個對象在一些值上迭代一次。更多關於迭代器here

在該螺紋,存在一個迭代用作extend()方法的自變量的例子:append vs. extend

相關問題