我在编写一些Python代码时偶然发现了令我感到意外的事情。我正在考虑复制一个列表,然后再添加一个元素重复的方法有两种:为什么列出`my_list + ['foo']`比`new_list = list(my_list)快; Python中的new_list.append('foo')`?
# I thought this would be clean-looking but slow since it creates an extra one element list, ['foo']
mylist = range(4)
newlist_0 = mylist + ['foo']
print newlist_0 # [0, 1, 2, 3, 'foo']
# I thought this would be faster
newlist_1 = list(mylist)
newlist_1.append('foo')
print newlist_1 # [0, 1, 2, 3, 'foo']
令人惊讶的是第一种方式,不仅好看,而且速度更快。我跑:
import timeit
for stmt in ['newlist_0 = mylist + ["foo"]', 'newlist_1 = list(mylist); newlist_1.append("foo")']:
print "For statement {:50} timeit results are {}".format(stmt, timeit.repeat(setup='mylist = range(4)', stmt=stmt))
,并得到这样的输出:
For statement newlist_0 = mylist + ["foo"] timeit results are [0.29012012481689453, 0.3021109104156494, 0.32175779342651367]
For statement newlist_1 = list(mylist); newlist_1.append("foo") timeit results are [0.39945101737976074, 0.39692091941833496, 0.38529205322265625]
暂时我无意中发现this question讨论的事实,list(lst)
比lst[:]
慢用于复制的列表,但切换到使用[:]
复制MYLIST没有按什么都不会改变。
函数调用开销 – wim 2014-09-01 18:06:03
@wim,那么我是否正确地推断,那么''''''''和''''''''''都不涉及函数调用,但是'append'呢? – kuzzooroo 2014-09-01 18:18:48