[英]In Python 3, what is the most efficient way to change the values in a list?
I'm learning Python, and I was trying to change a list in different ways. 我正在学习Python,我试图以不同的方式更改列表。 For instance, if I have list called names like this: 例如,如果我有名单这样的名称:
names = ["David", "Jake", "Alex"]
and I want to add the name "Carter" into the list, what is the most efficient way to accomplish this? 我想在列表中添加名称“Carter”,实现这一目标的最有效方法是什么? Here's some of the things I can do: 以下是我可以做的一些事情:
names.append("Carter")
names = names + ["Carter"]
names += ["Carter"]
append is the fastest. 追加是最快的。 Here is how you build a small profile using the timeit module 以下是使用timeit模块构建小型配置文件的方法
import timeit
a = (timeit.timeit("l.append('Cheese')", setup="l=['Meat', 'Milk']"))
b = (timeit.timeit("l+=['Cheese']", setup="l=['Meat', 'Milk']"))
c = (timeit.timeit("append('Cheese')", setup="l=['Meat', 'Milk'];append = l.append"))
print ('a', a)
print ('b', b)
print ('c', c)
print ("==> " , (c < a < b))
As you can see, In python the access to the method append takes half of the time as the l.append itself... 正如您所看到的,在python中,对方法append的访问占用了l.append本身的一半时间...
a 0.08502503100316972 a 0.08502503100316972
b 0.1582659209962003 b 0.1582659209962003
c 0.041991976962890476 c 0.041991976962890476
==> True ==>是的
You can use the timeit
package as shown in this blog post . 您可以使用此博客文章中显示的timeit
包。
Here is a complete code running the tests 20000 times each test: 以下是每个测试运行20000次测试的完整代码:
import timeit t = 20000 print( "Addition (lst = lst + [4, 5, 6])" ) print( timeit.Timer("lst = lst + [4, 5, 6]", "lst = [1, 2, 3]").timeit(t) ) print( "Addition (lst += [4, 5, 6])" ) print( timeit.Timer("lst += [4, 5, 6]", "lst = [1, 2, 3]").timeit(t) ) print( "Extend (lst.extend([4, 5, 6]))" ) print( timeit.Timer("lst.extend([4, 5, 6])", "lst = [1, 2, 3]").timeit(t) ) print( "Append loop (lst.append([4, 5, 6]))" ) print( timeit.Timer("for i in [4,5,6]: lst.append(i)", "lst = [1,2,3]").timeit(t) ) print( "Append loop, no dot (a(i))" ) # a.b does a lookup, we don't want that, it is slower. Instead use b = a.b # then use b. print( timeit.Timer("""a = lst.append for i in [4,5,6]: a(i)""", "lst = [1,2,3]").timeit(t) )
And the results (Python 3.4.4) are: 结果(Python 3.4.4)是:
Addition (lst = lst + [4, 5, 6]) 1.947201736000352 Addition (lst += [4, 5, 6]) 0.0015889199999037373 Extend (lst.extend([4, 5, 6])) 0.0020685689996753354 Append loop (lst.append([4, 5, 6])) 0.0047527769997941505 Append loop, no dot (a(i)) 0.003853704999983165
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.