我需要从Python 2.7中的对象列表中删除前n个元素。是否有一种简便的方法,而不使用循环?
我需要从Python 2.7中的对象列表中删除前n个元素。是否有一种简便的方法,而不使用循环?
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist
输出:
[6, 7, 8, 9]
或者使用 del
如果你只想使用一个列表:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist
输出:
[6, 7, 8, 9]
Python列表并不适用于在列表开头进行操作,并且在这种操作上非常低效。
虽然你可以编写
mylist = [1, 2 ,3 ,4]
mylist.pop(0)
非常低效。
如果你只想从列表中删除项目,可以使用del
:
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 的 collections.deque
和它的 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'
比较:
In [30]: %%timeit
....: help=range(10000)
....: while help:
....: help.pop(0)
....:
100 loops, best of 3: 17.9 ms per loop
In [33]: %%timeit
help=deque(range(10000))
while help:
help.popleft()
....:
1000 loops, best of 3: 812 µs per loop
list
是基于数组的,那么pop
如何高效呢?https://wiki.python.org/moin/TimeComplexity - Ciro Santilli OurBigBook.comdeque
与list
的比较,请记住,deque
并没有list
拥有的所有功能。在处理更大的移位(100万行)时,我发现del mylist[1000000:]
的执行时间与deque.popleft()
对于所有行来说大致相同。因此,这取决于您的使用情况。 - gies0rpopleft()
时可以迭代 deque 吗? - Christianl = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.
l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.
popped_items = lst[:n]
del lst[:n]
它允许您首先获取前n个项目并仅为它们分配空间。然后,您可以从初始列表中删除它们,这也很快。
请尝试运行以下代码:
del x[:N]
mylist = [1,2,3,4,5,6,7,8,9]
您想要删除最后x
个元素并将它们存储在另一个列表中。
newlist = [mylist.pop() for _ in range(x)]
newlist = [mylist.pop(0) for _ in range(x)]
要么保留第一个元素,要么移除x
个元素
newlist = [mylist.pop(1) for _ in range(x)]
l = [5,1,4,2,3,6]
l.sort()
移除列表中的前两个项目
for _ in range(2)
l.remove(l[0])
打印列表
print(l)
x.pop(5)
,del x[5]
或x.remove("cow")
。前两个是通过索引删除,后者是通过搜索条件删除。第二种方法可以通过执行del x[2:5]
来组合删除索引 2-5。 - Torxedpos = x.index("f"); end = x.index("z"); del x[pos:end]
。你需要考虑到z
可能会在f
之前出现,并且在搜索z
时使用pos
作为起始点等,但你已经明白了。 - Torxed