为什么扩展python列表

rob*_*ing 7 python merge list append extend

为什么在使用+ =运算符时使用extend?哪种方法最好?另外,将多个列表合并到一个列表中的最佳方法是什么

#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]
Run Code Online (Sandbox Code Playgroud)

qia*_*iao 16

+=只能用于通过另一个列表扩展一个列表,而extend可以用于通过可迭代对象扩展一个列表

例如

你可以做

a = [1,2,3]
a.extend(set([4,5,6]))
Run Code Online (Sandbox Code Playgroud)

但你做不到

a = [1,2,3]
a += set([4,5,6])
Run Code Online (Sandbox Code Playgroud)

对于第二个问题

[item for sublist in l for item in sublist] is faster.
Run Code Online (Sandbox Code Playgroud)

请参阅Python中列表中的列表