在python中扩展数组前端的最快方法是什么?可以说我有2个数组:
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 s

测试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(因此,我们的目的不适合):
测试“错误”:
a,b = [],[]
for i in range(0,100000):
    a.append(i)
    b.append(i)

def f(a,b):
    for i in range(0,100):
        b.extend(a)

import cProfile
cProfile.run('f(a,b)')

时间:〜0.13s

因此,理论上应该有一种方法可以延长测试“错误”的时间。

最佳答案

绝对最快的方法是使用针对此用途进行了优化的 collections.deque ,并使用名为.appendleft.extendleft的方法使代码美观且可读-appendleft完全按照其在锡盒上的说明进行操作(即,它追加到左侧的双端队列),而extendleft等效于:

def extendleft(self, other)
    for item in other:
        self.appendleft(c)

因此,a = b+a将被拼写为:
a.extendleft(reversed(b))

09-07 06:02