我正在学习Python,我试图以不同的方式更改列表。例如,如果我有名单这样的名称:
names.append("Carter")
names = names + ["Carter"]
names += ["Carter"]
我希望将名称“Carter”添加到列表中,实现此目的的最有效方法是什么?以下是我可以做的一些事情:
{{1}}
答案 0 :(得分:7)
追加是最快的。 以下是使用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))
正如您所看到的,在python中,对方法append的访问占用了 l.append 本身的一半时间......
a 0.08502503100316972
b 0.1582659209962003
c 0.041991976962890476
==&GT;真
答案 1 :(得分:1)
您可以使用此blog post中显示的timeit
包。
以下是每个测试运行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) )
结果(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