sor*_*rin 13 python performance list
你有
x = ['a', 'b', 'c']
y = [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
并希望y在开头插入列表x:
x = [1, 2, 3, 'a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)
在Python中执行此操作的最佳解决方案是什么?
Fre*_*Foo 13
如果要在左侧追加,则a deque比列表更有效.使用该extendleft方法.
>>> from collections import deque
>>> d = deque(['a', 'b', 'c'])
>>> d.extendleft(reversed([1, 2, 3]))
>>> d
deque([1, 2, 3, 'a', 'b', 'c'])
Run Code Online (Sandbox Code Playgroud)
如果您始终只在左侧附加,请考虑以相反的顺序将元素保留在列表中.
Ash*_*ary 13
>>> x = ['a', 'b', 'c']
>>> y = [1, 2, 3]
>>> x = y+x
Run Code Online (Sandbox Code Playgroud)
deque对于较小的输入尺寸,这个简单的解决方案运行速度是解决方案的两倍:
$ cat x1.py
for i in range(1000000):
x = ['a', 'b', 'c']
y = [1, 2, 3]
x = y+x
$ cat x2.py
from collections import deque
for i in range(1000000):
d = deque(['a', 'b', 'c'])
d.extendleft(reversed([1, 2, 3]))
$ time python x1.py
real 0m1.912s
user 0m1.864s
sys 0m0.040s
$ time python x2.py
real 0m5.368s
user 0m5.316s
sys 0m0.052s
Run Code Online (Sandbox Code Playgroud)
但是,对于较大尺寸的输入,它会变慢:
>python -m timeit -s "y = range(100000)" "x = list(xrange(10000000)); y+x"
10 loops, best of 3: 229 msec per loop
>python -m timeit -s "from collections import deque; y = range(100000)" "d = deque(xrange(10000000)); d.extendleft(reversed(y))"
10 loops, best of 3: 178 msec per loop
Run Code Online (Sandbox Code Playgroud)
根据您对结果的处理,您可能根本不想制作列表:
new_x = itertools.chain(y, x)
Run Code Online (Sandbox Code Playgroud)
现在你有一个迭代器,它将生成y中的所有值,然后生成x中的所有值.现在你可以迭代它:
for val in new_x:
blah blah
Run Code Online (Sandbox Code Playgroud)
x[0:0] = y
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7538 次 |
| 最近记录: |