Python列表并未在列表的开头进行操作,并且在此操作中非常无效。

虽然你可以写

mylist = [1, 2 ,3 ,4]
mylist.pop(0)

这是非常低效的。

如果只想从列表中删除项目,则可以使用popleft()进行以下操作:

del mylist[:n]

这也真的很快:

In [34]: %%timeit
help=range(10000)
while help:
del help[:1000]
....:
10000 loops, best of 3: 161 µs per loop

如果需要从列表的开头获取元素,则应使用Raymond Hettinger的popleft()及其popleft()方法。

from collections import deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'

一个对比:

清单+弹出(0)

In [30]: %%timeit
....: help=range(10000)
....: while help:
....: help.pop(0)
....:
100 loops, best of 3: 17.9 ms per loop
deque + popleft()
In [33]: %%timeit
help=deque(range(10000))
while help:
help.popleft()
....:
1000 loops, best of 3: 812 µs per loop