在 Python 3 中,更改列表中的值最有效的方法是什么?

In Python 3, what is the most efficient way to change the values in a list?

我正在学习 Python,我正在尝试以不同的方式更改列表。例如,如果我有这样的名字列表:

names = ["David", "Jake", "Alex"]

我想将名字 "Carter" 添加到列表中,最有效的方法是什么?以下是我可以做的一些事情:

names.append("Carter")

names = names + ["Carter"]

names += ["Carter"]

追加是最快的。 以下是使用 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

==> True

您可以使用 timeit 包,如此 blog post 所示。

这里是一个完整的代码运行测试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