我的代码有问题吗?deque
当使用collections
模块而不是常规列表来计时一个简单的函数时,我的速度提高了 100 倍。
>>> from collections import deque as dl
>>> import cProfile
>>>
>>> def l(i):
... l = ['0','1','2','3','4','5','6']
... while i:
... l.insert(0,'9')
... i -= 1
...
>>> def d(i):
... l = dl('0123456')
... while i:
... l.appendleft('9')
... i -= 1
...
>>> cProfile.run('l(100000)')
100004 function calls in 4.480 seconds
[...]
>>> cProfile.run('d(100000)')
100004 function calls in 0.031 seconds
如果我的代码没问题,那么使用列表有什么意义呢?为什么不完全切换到deque
?