列表方法append()
和extend()
什么区别? python
如下两个片断在语义上是等效的: app
for item in iterator: a_list.append(item)
和 函数
a_list.extend(iterator)
当循环在C中实现时,后者可能会更快。 spa
extend()
能够与迭代器参数一块儿使用。 这是一个例子。 您但愿经过如下方式从列表列表中列出一个列表: code
从 对象
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
你要 element
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
您可使用itertools.chain.from_iterable()
进行操做。 该方法的输出是一个迭代器。 它的实现等效于 get
def from_iterable(iterables): # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F for it in iterables: for element in it: yield element
回到咱们的例子,咱们能够作 博客
import itertools list2d = [[1,2,3],[4,5,6], [7], [8,9]] merged = list(itertools.chain.from_iterable(list2d))
并得到通缉名单。 it
这是等效地extend()
与迭代器参数一块儿使用的方式:
merged = [] merged.extend(itertools.chain.from_iterable(list2d)) print(merged) >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
append(object)
-经过将对象添加到列表来更新列表。
x = [20] # List passed to the append(object) method is treated as a single object. x.append([21, 22, 23]) # Hence the resultant list length will be 2 print(x) --> [20, [21, 22, 23]]
extend(list)
-本质上是串联两个列表。
x = [20] # The parameter passed to extend(list) method is treated as a list. # Eventually it is two lists being concatenated. x.extend([21, 22, 23]) # Here the resultant list's length is 4 print(x) [20, 21, 22, 23]
您可使用“ +”返回扩展名,而不是就地扩展名。
l1=range(10) l1+[11] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11] l2=range(10,1,-1) l1+l2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]
相似地, +=
用于就地行为,但与append
和extend
略有不一样。 +=
与append
和extend
的最大区别之一是在函数范围内使用它时,请参阅此博客文章 。
append()
方法将单个项目添加到列表的末尾。
x = [1, 2, 3] x.append([4, 5]) x.append('abc') print(x) # gives you [1, 2, 3, [4, 5], 'abc']
extend()
方法采用一个参数,一个列表,并将该参数的每一个项目附加到原始列表中。 (列表做为类实现。“建立”列表其实是在实例化一个类。所以,列表具备对其进行操做的方法。)
x = [1, 2, 3] x.extend([4, 5]) x.extend('abc') print(x) # gives you [1, 2, 3, 4, 5, 'a', 'b', 'c']
从潜入Python 。