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