Red*_*vet 56 python performance list python-2.7 python-3.x
我需要从Python 2.7中的对象列表中删除前n个元素.有没有使用循环的简单方法?
Avi*_*ión 67
您可以使用列表切片来存档目标:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist
Run Code Online (Sandbox Code Playgroud)
输出:
[6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
或者,del
如果您只想使用一个列表:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist
Run Code Online (Sandbox Code Playgroud)
输出:
[6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
Seb*_*zny 38
Python列表不是在列表的开头操作,而是在此操作中非常无效.
虽然你可以写
mylist = [1, 2 ,3 ,4]
mylist.pop(0)
Run Code Online (Sandbox Code Playgroud)
这是非常低效的.
如果您只想从列表中删除项目,可以执行以下操作del
:
del mylist[:n]
Run Code Online (Sandbox Code Playgroud)
哪个也很快:
In [34]: %%timeit
help=range(10000)
while help:
del help[:1000]
....:
10000 loops, best of 3: 161 µs per loop
Run Code Online (Sandbox Code Playgroud)
如果您需要从列表的开头获取元素,您应该使用collections.deque
Raymond Hettinger及其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'
Run Code Online (Sandbox Code Playgroud)
一个对比:
In [30]: %%timeit
....: help=range(10000)
....: while help:
....: help.pop(0)
....:
100 loops, best of 3: 17.9 ms per loop
Run Code Online (Sandbox Code Playgroud)
In [33]: %%timeit
help=deque(range(10000))
while help:
help.popleft()
....:
1000 loops, best of 3: 812 µs per loop
Run Code Online (Sandbox Code Playgroud)
小智 5
l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.
Run Code Online (Sandbox Code Playgroud)
如果您想从列表中删除多个项目,请使用此代码。您也可以跳过冒号之前的零。它没有那么重要。这或许也可以。
l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.
Run Code Online (Sandbox Code Playgroud)