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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33626623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:38:58  来源:igfitidea点击:

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

pythonperformancelistpython-2.7python-3.x

提问by RedVelvet

I need to remove the first n elements from a list of objects in Python 2.7. Is there an easy way, without using loops?

我需要从 Python 2.7 中的对象列表中删除前 n 个元素。有没有不使用循环的简单方法?

采纳答案by Avión

You can use list slicing to archive your goal:

您可以使用列表切片来归档您的目标:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist

Outputs:

输出:

[6, 7, 8, 9]

Or delif you only want to use one list:

或者,del如果您只想使用一个列表:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist

Outputs:

输出:

[6, 7, 8, 9]

回答by Sebastian Wozny

Python lists were not made to operate on the beginning of the list and are very ineffective at this operation.

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

While you can write

虽然你可以写

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

It's veryinefficient.

这是非常低效的。



If you only want to delete items from your list, you can do this with del:

如果您只想从列表中删除项目,您可以使用del

del mylist[:n]

Which is also really fast:

这也非常快:

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


If you need to obtain elements from the beginning of the list, you should use collections.dequeby Raymond Hettinger and its popleft()method.

如果需要从列表的开头获取元素,则应使用collections.dequeby 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'

A comparison:

一个对比:

list + pop(0)

列表 + 弹出(0)

In [30]: %%timeit
   ....: help=range(10000)
   ....: while help:
   ....:     help.pop(0)
   ....:
100 loops, best of 3: 17.9 ms per loop

deque + popleft()

双端队列 + popleft()

In [33]: %%timeit
help=deque(range(10000))
while help:
    help.popleft()
   ....:
1000 loops, best of 3: 812 μs per loop

回答by Mangu Singh Rajpurohit

Try to run this code:

尝试运行此代码:

del x[:N]

回答by Avión

l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.

This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.

如果您想从列表中删除多个项目,这是代码。您不妨跳过冒号前的零。它没有那么重要。这也可以。

l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.