快速python前端列表扩展
在python中扩展数组前端的最快方法是什么?假设我有两个阵列: a和b。我想用最快的方法a=b+a(b不应该改变) 我的小板凳: 测试1:快速python前端列表扩展,python,performance,list,profiling,concatenation,Python,Performance,List,Profiling,Concatenation,在python中扩展数组前端的最快方法是什么?假设我有两个阵列: a和b。我想用最快的方法a=b+a(b不应该改变) 我的小板凳: 测试1: a,b = [],[] for i in range(0,100000): a.append(i) b.append(i) def f(a,b): for i in range(0,100): a=a+b import cProfile cProfile.run('f(a,b)') 时间:~12秒 测试2: a
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
def f(a,b):
for i in range(0,100):
a=a+b
import cProfile
cProfile.run('f(a,b)')
时间:~12秒
测试2:
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
def f(a,b):
for i in range(0,100):
a[0:0] = b
import cProfile
cProfile.run('f(a,b)')
时间:~1.5秒
测试3:
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
lenb = len(b)
def f(a,b):
for i in range(0,100):
b.extend(a)
# do something with b
b = b[:lenb]
import cProfile
cProfile.run('f(a,b)')
时间:~0.4s
但我认为它应该更快,因为列表串联应该作为一些底层指针的改变而进行。
下面的代码是最快的代码,但是更改了b,而不是a(因此不适合我们的目的):
测试“错误”:
时间:~0.13秒
因此,理论上应该有一种方法可以在测试“错误”时延长a的前端。绝对最快的方法是使用经过优化的a,并且具有名为
.appendleft
和.extendleft
的方法,以使代码美观易读-appendleft
完全按照tin上的说明执行(即,它附加到deque的左侧),而extendleft
执行以下操作:
def extendleft(self, other)
for item in other:
self.appendleft(c)
因此,a=b+a
将拼写为:
a.extendleft(reversed(b))
from collections import deque
注意,您拥有的是列表,而不是数组。您希望使用a.extendleft(反向(b))
,因为extendleft
从头部消耗给定的iterable(就像蛇吃老鼠一样)。
a.extendleft(reversed(b))