反转附加列表或添加列表是否更便宜? – Python
作者:互联网
哪个更快更pythonic?
>反转附加列表
>从头开始预先开始列表
>使用deque
例如.这是用于存储到新列表中的ome组成数据
# Let's say my function outputs these output individually.
x = [12,34,44,346,345,876,123]
反转附加列表:
new_list = []
for i in x:
new_list.append(i)
new_list = newlist[::-1]
在列表前面:
new_list = []
for i in x:
new_list.insert(0,i)
使用deque:
from collections import deque
for i in x:
x.appendleft(i)
请注意,我的问题不是如何反转列表.还请假设列表大小约为20,000.
解决方法:
您的第一种方法可以简化为一行:
new_list = x[::-1]
然后,要检查哪个方法比任何其他方法更快,只需使用timeit(使用python 2.7.8测试):
C:\>python -m timeit -s "x = [12,34,44,346,345,876,123]" "new_list = x[::-1]"
1000000 loops, best of 3: 0.215 usec per loop
C:\>python -m timeit -s "x = [12,34,44,346,345,876,123]; new_list = []" "for i in x:" " new_list.insert(0,i)"
10000 loops, best of 3: 146 usec per loop
C:\>python -m timeit -s "from collections import deque; x = [12,34,44,346,345,876,123]; new_list = deque()" "for i in x:" " new_list.appendleft(i)"
1000000 loops, best of 3: 0.713 usec per loop
C:\>python -m timeit -s "x = [12,34,44,346,345,876,123]" "new_list = list(reversed(x))"
1000000 loops, best of 3: 0.837 usec per loop
所以new_list = x [:: – 1]比任何其他方式都要好.
您还必须问自己是否要“引用”或“复制”元素到新的列表结构中.
标签:python,insert,reverse,list,prepend 来源: https://codeday.me/bug/20190703/1363598.html