繁体   English   中英

删除列表中前 N 个元素的最有效方法?

[英]The most efficient way to remove first N elements in a list?

我需要从 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及其popleft()方法的collections.deque

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'

一个对比:

list + pop(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
l = [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.

尝试运行此代码:

del x[:N]
l = [5,1,4,2,3,6]

将列表从小到大排序

l.sort()

删除列表中的前 2 项

for _ in range(2)
    l.remove(l[0])

打印列表

print(l)

假设你有这个列表:

mylist = [1,2,3,4,5,6,7,8,9]

并且您想删除x最后一个元素并将它们存储在另一个列表中

newlist = [mylist.pop() for _ in range(x)]

您可以修改传递给 pop 的参数,以便从头开始删除元素

newlist = [mylist.pop(0) for _ in range(x)]

或者保留第一个元素并在之后删除x元素

newlist = [mylist.pop(1) for _ in range(x)]

最有效的方法,内存方面和复杂性方面,是这样的:

popped_items = lst[:n]
del lst[:n]

它允许您首先获取前 n 个项目,并只为它们分配空间。 然后,您从初始列表中删除它们,这也很快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM