在Python中,“.append()"和".append()"之间有什么区别?和"+ = []"? [英] In Python, what is the difference between ".append()" and "+= []"?
问题描述
两者之间有什么区别
some_list1 = []
some_list1.append("something")
和
some_list2 = []
some_list2 += ["something"]
推荐答案
对于您而言,唯一的区别是性能:append的速度是原来的两倍.
For your case the only difference is performance: append is twice as fast.
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
会将一个项目添加到列表中,而+=
会将右侧列表的 all 个元素复制到左侧列表中.
In general case append
will add one item to the list, while +=
will copy all elements of right-hand-side list into the left-hand-side list.
更新:性能分析
比较字节码,我们可以假定append
版本浪费了LOAD_ATTR
+ CALL_FUNCTION
的周期,而+ =版本浪费了BUILD_LIST
的周期.显然,BUILD_LIST
胜过LOAD_ATTR
+ CALL_FUNCTION
.
Comparing bytecodes we can assume that append
version wastes cycles in LOAD_ATTR
+ CALL_FUNCTION
, and += version -- in BUILD_LIST
. Apparently BUILD_LIST
outweighs 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
开销来进一步提高性能:
We can improve performance even more by removing LOAD_ATTR
overhead:
>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566
这篇关于在Python中,“.append()"和".append()"之间有什么区别?和"+ = []"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!