爲什麼使用擴展當你只能使用+ =運算符?哪種方法最好? 還什麼是連接多個列出一個列表中的最佳方式爲什麼要擴展一個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]
謝謝!這很適合它。 _list + = list(_iterable)是否相等? – 2012-01-08 05:27:53
可以實現相同的結果,但底層的實現會有所不同。 – qiao 2012-01-08 05:32:34