反向追加列表或在列表前面便宜吗?-蟒蛇

alv*_*vas 5 python reverse list insert prepend

哪个更快,更pythonic?

  • 反转附加列表
  • 从头开始将列表放在前面
  • 使用 deque

例如,这里有一些人造数据要存储到新列表中

# Let's say my function outputs these output individually.
x = [12,34,44,346,345,876,123]
Run Code Online (Sandbox Code Playgroud)

反转附加列表:

new_list = []
for i in x:
  new_list.append(i)
new_list = newlist[::-1]
Run Code Online (Sandbox Code Playgroud)

在列表之前:

new_list = [] 
for i in x:
  new_list.insert(0,i)
Run Code Online (Sandbox Code Playgroud)

使用双端队列:

from collections import deque
for i in x:
  x.appendleft(i)
Run Code Online (Sandbox Code Playgroud)

请注意,我的问题不是如何反向列出。还请假设列表的大小约为20,000。

Jér*_*dix 4

您的第一个方法可以简化为一行:

new_list = x[::-1]
Run Code Online (Sandbox Code Playgroud)

然后,要检查哪种方法比其他方法更快,只需使用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
Run Code Online (Sandbox Code Playgroud)

所以new_list = x[::-1]比任何其他方式都要好。

您还必须问自己是否要将元素“引用”或“复制”到新的列表结构中。