[英]What is the difference between Python's list methods append and extend?
[英]In Python, what is the difference between ".append()" and "+= []"?
有什么區別:
some_list1 = []
some_list1.append("something")
和
some_list2 = []
some_list2 += ["something"]
對於您的情況,唯一的區別是性能:附加速度是原來的兩倍。
Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.20177424499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.41192320500000079
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.23079359499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.44208112500000141
一般情況下append
會將一項添加到列表中,而+=
會將右側列表的所有元素復制到左側列表中。
更新:性能分析
比較字節碼,我們可以假設append
版本浪費了LOAD_ATTR
+ CALL_FUNCTION
和 += version -- 在BUILD_LIST
中的周期。 顯然BUILD_LIST
超過LOAD_ATTR
+ CALL_FUNCTION
。
>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_ATTR 1 (append)
12 LOAD_CONST 0 ('spam')
15 CALL_FUNCTION 1
18 POP_TOP
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_CONST 0 ('spam')
12 BUILD_LIST 1
15 INPLACE_ADD
16 STORE_NAME 0 (s)
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
我們可以通過消除LOAD_ATTR
開銷來進一步提高性能:
>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566
在您給出的示例中,就輸出而言, append
和+=
之間沒有區別。 但是append
和+
(這個問題最初是關於這個問題的)是有區別的。
>>> a = []
>>> id(a)
11814312
>>> a.append("hello")
>>> id(a)
11814312
>>> b = []
>>> id(b)
11828720
>>> c = b + ["hello"]
>>> id(c)
11833752
>>> b += ["hello"]
>>> id(b)
11828720
如您所見, append
和+=
具有相同的結果; 他們將項目添加到列表中,而不生成新列表。 使用+
添加兩個列表並生成一個新列表。
>>> a=[]
>>> a.append([1,2])
>>> a
[[1, 2]]
>>> a=[]
>>> a+=[1,2]
>>> a
[1, 2]
看到 append 將單個元素添加到列表中,這可能是任何東西。 +=[]
加入列表。
+= 是一個任務。 當你使用它時,你實際上是在說 'some_list2= some_list2+['something']'。 作業涉及重新綁定,因此:
l= []
def a1(x):
l.append(x) # works
def a2(x):
l= l+[x] # assign to l, makes l local
# so attempt to read l for addition gives UnboundLocalError
def a3(x):
l+= [x] # fails for the same reason
+= 運算符通常也應該像 list+list 通常那樣創建一個新的列表對象:
>>> l1= []
>>> l2= l1
>>> l1.append('x')
>>> l1 is l2
True
>>> l1= l1+['x']
>>> l1 is l2
False
然而在現實中:
>>> l2= l1
>>> l1+= ['x']
>>> l1 is l2
True
這是因為 Python 列表實現了 __iadd__()以使 += 增強賦值短路並改為調用 list.extend() 。 (這有點奇怪:它通常按照你的意思做,但出於令人困惑的原因。)
一般來說,如果您要附加/擴展現有列表,並且希望保留對同一列表的引用(而不是創建新列表),最好明確並堅持使用 append()/extend()方法。
some_list2 += ["something"]
實際上是
some_list2.extend(["something"])
對於一個值,沒有區別。 文檔指出:
s.append(x)
與s[len(s):len(s)] = [x]
相同
s.extend(x)
與s[len(s):len(s)] = x
相同
因此顯然s.append(x)
與s.extend([x])
相同
will flatten the resulting list, whereas will keep the levels intact:不同之處在於將使結果列表變平,而將保持級別不變:
例如:
myList = [ ]
listA = [1,2,3]
listB = ["a","b","c"]
使用 append,您最終會得到一個列表列表:
>> myList.append(listA)
>> myList.append(listB)
>> myList
[[1,2,3],['a','b','c']]
使用 concatenate 代替,你最終得到一個平面列表:
>> myList += listA + listB
>> myList
[1,2,3,"a","b","c"]
這里的性能測試不正確:
append
與+=[]
,則應append
聲明為本地函數。例如
timeit.Timer('for i in xrange(100): app(i)', 's = [] ; app = s.append').timeit()
可以在這里找到好的測試: Python list append vs. +=[]
除了其他答案中描述的方面之外, append 和 +[] 在您嘗試構建列表時具有非常不同的行為。
>>> list1=[[1,2],[3,4]]
>>> list2=[5,6]
>>> list3=list1+list2
>>> list3
[[1, 2], [3, 4], 5, 6]
>>> list1.append(list2)
>>> list1
[[1, 2], [3, 4], [5, 6]]
list1+['5','6'] 將 '5' 和 '6' 作為單獨的元素添加到 list1 中。 list1.append(['5','6']) 將列表 ['5','6'] 作為單個元素添加到 list1。
其他答案中提到的重新綁定行為在某些情況下確實很重要:
>>> a = ([],[])
>>> a[0].append(1)
>>> a
([1], [])
>>> a[1] += [1]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
那是因為增強的賦值總是重新綁定,即使對象在原地發生了變異。 這里的重新綁定恰好是a[1] = *mutated list*
,它不適用於元組。
“+”不會改變列表
.append () 改變舊列表
我們先舉個例子
list1=[1,2,3,4]
list2=list1 (that means they points to same object)
if we do
list1=list1+[5] it will create a new object of list
print(list1) output [1,2,3,4,5]
print(list2) output [1,2,3,4]
but if we append then
list1.append(5) no new object of list created
print(list1) output [1,2,3,4,5]
print(list2) output [1,2,3,4,5]
extend(list) also do the same work as append it just append a list instead of a
single variable
append() 方法將單個項目添加到現有列表
some_list1 = []
some_list1.append("something")
所以這里 some_list1 將被修改。
更新:
而使用 + 組合現有列表中的列表元素(多個元素)類似於擴展(由Flux更正)。
some_list2 = []
some_list2 += ["something"]
所以這里的 some_list2 和 ["something"] 是兩個組合在一起的列表。
截至今天和 Python 3.6,@Constantine 提供的結果不再相同。
Python 3.6.10 |Anaconda, Inc.| (default, May 8 2020, 02:54:21)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.0447923709944007
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.04335783299757168
似乎append
和+=
現在具有相同的性能,而編譯差異根本沒有改變:
>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
1 0 BUILD_LIST 0
2 STORE_NAME 0 (s)
4 LOAD_NAME 0 (s)
6 LOAD_ATTR 1 (append)
8 LOAD_CONST 0 ('spam')
10 CALL_FUNCTION 1
12 POP_TOP
14 LOAD_CONST 1 (None)
16 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
1 0 BUILD_LIST 0
2 STORE_NAME 0 (s)
4 LOAD_NAME 0 (s)
6 LOAD_CONST 0 ('spam')
8 BUILD_LIST 1
10 INPLACE_ADD
12 STORE_NAME 0 (s)
14 LOAD_CONST 1 (None)
16 RETURN_VALUE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.