python中“+=”操作与“+”操作

先来看段代码:

from timeit import Timer

def test1():
   l = []
   for i in range(1000):
      l = l + [i]
def test2():
   l = []
   for i in range(1000):
      l.append(i)
def test3():
   l = []
   for i in range(1000):
      l += [i]

t1 = Timer("test1()", "from __main__ import test1")
print("+ ",t1.timeit(number=1000), "seconds")
t2 = Timer("test2()", "from __main__ import test2")
print("append ",t2.timeit(number=1000), "seconds")
t3 = Timer("test3()", "from __main__ import test3")
print("+= ",t3.timeit(number=1000), "seconds")

结果为:

('+ ', 1.1890289783477783, 'seconds')
('append ', 0.06389594078063965, 'seconds')
('+= ', 0.09289216995239258, 'seconds')

从结果可以看出,“ l += [i]”的效率远远高于“l = l + [i]”,“ l += [i]”的效率跟“l.append(i)”差不多
这是因为“ l += [i]”跟“l.append(i)”是直接作用于list对象上的,而“l = l + [i]”是先在等号右边创建一个新的列表“ l + [i]”,然后在放到等号左边的“l”中。
所以在python中“+”操作效率时很低的,应尽量避免使用来提高程序的效率。

点赞