Python-附加VS扩展效率 [英] Python - append VS extend efficiency
问题描述
这是我使用Python编写的一些代码:
Here is some code that I wrote using Python:
from math import sqrt
abundant_list = []
for i in range(12,28123+1):
dividor_list = [1]
for j in range(2, int(sqrt(i))+1):
if i%j == 0:
dividor_list.extend([i/j,j])
if sum(dividor_list) > i:
abundant_list.append(i)
print abundant_list
如您所见,代码实际上是在尝试尽可能地提高效率.
As you can see, the code is really trying to be efficient as much as possible.
两次使用list.append
还是一次使用list.extend
有什么区别?
我知道这可能是微小的差异,但是我真的很想知道:)
There is any difference if I use list.append
twice, or list.extend
just once?
I know it can be minor differences, but I would really like to know that :)
推荐答案
import timeit
def append2x(foo):
foo.append(1)
foo.append(1)
def extend_lst(foo):
foo.extend([1,1])
def extend_tup(foo):
foo.extend((1,1))
l1 = []
l2 = []
l3 = []
print timeit.timeit('append2x(l1)',setup = 'from __main__ import append2x,l1')
print timeit.timeit('extend_lst(l2)',setup = 'from __main__ import extend_lst,l2')
print timeit.timeit('extend_tup(l3)',setup = 'from __main__ import extend_tup,l3')
这是一个简单的基准.我的结果(os-X,10.5.8,core2duo,FWIW):
Here's a simple benchmark. My results (os-X, 10.5.8, core2duo, FWIW):
0.520906925201 #append
0.602569103241 #extend-list
0.357008934021 #extend-tuple
结果与Linux盒中的结果相同(Ubuntu,x86-64核心i7):
And the same ordering of the results my linux box (Ubuntu, x86-64 core i7):
0.307395935059 #append
0.319436073303 #extend-list
0.238317012787 #extend-tuple
对我来说,这表示extend
比append
快,但是与创建tuple
To me, this says that extend
is quicker than append
, but that creating a list
is relatively expensive compared to creating a tuple
在下面的注释中指出,由于元组的不变性,解释器可以优化元组的创建(它会创建一次元组并反复使用它).如果我们将代码更改为:
Pointed out in the comments below, because of the immutability of tuples, the interpreter can optimize the creation of the tuple out (it creates the tuple once and re-uses it over and over). If we change the code to:
def extend_lst(foo):
v = 1
foo.extend([v,v])
def extend_tup(foo):
v = 1
foo.extend((v,v))
时间实际上是相同的:
0.297003984451 #append
0.344678163528 #extend-list
0.292304992676 #extend-tuple
尽管tuple
仍然始终胜过列表版本,并且在我所做的所有试验中都勉强超越了append
版本.
Although tuple
still consistently beats the list version and barely edges out the append
version for all of the trials I have done.
我要摆脱的一件事是,如果要遍历包含所有文字的对象,请选择tuple
而不是list
.如果它不完全由文字组成,那么选择list
还是tuple
都没关系.
One thing that I'm taking away from this is that if you're iterating over an object that consists of all literals, choose a tuple
over a list
. If it doesn't consist entirely of literals, then it really doesn't matter whether you choose list
or tuple
.
这篇关于Python-附加VS扩展效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!