Python 删除列表的最后 N 个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15715912/
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-18 20:45:30  来源:igfitidea点击:

Remove the last N elements of a list

pythonlist

提问by Theo

Is there a a better way to remove the last N elements of a list.

有没有更好的方法来删除列表的最后 N 个元素。

for i in range(0,n):
    lst.pop( )

采纳答案by karthikr

if you wish to remove the last n elements, in other words, keep first len - n elements:

如果你想删除最后 n 个元素,换句话说,保留第一个 len - n 个元素:

lst = lst[:len(lst)-n]

Note: This is not an in memory operation. It would create a shallow copy.

注意:这不是内存操作。它会创建一个浅拷贝。

回答by jamylak

Works for n >= 1

效劳于 n >= 1

>>> L = [1,2,3, 4, 5]
>>> n=2
>>> del L[-n:]
>>> L
[1, 2, 3]

回答by Yarkee

Just try to del it like this.

试着像这样删除它。

del list[-n:]

回答by chamini2

I see this was asked a long ago, but none of the answers did itfor me; what if we want to get a list without the last N elements, but keep the original one: you just do list[:-n]. If you need to handle cases where nmay equal 0, you do list[:-n or None].

我看到这个被问得早,但没有一个答案做了我; 如果我们想得到一个没有最后 N 个元素的列表,但保留原始元素,该怎么办:你只需要list[:-n]. 如果您需要处理n可能相等的情况0,您可以这样做list[:-n or None]

>>> a = [1,2,3,4,5,6,7]
>>> b = a[:-4]
>>> b
[1, 2, 3]
>>> a
[1, 1, 2, 3, 4, 5, 7]

As simple as that.

就如此容易。

回答by Vincenzooo

This is one of the cases in which being pythonicdoesn't work for me and can give hidden bugs or mess. None of the solutions above works for the case n=0. Using l[:len(l)-n]works in the general case:

这是存在pythonic对我不起作用的情况之一,并且可能会产生隐藏的错误或混乱。上述解决方案均不适用于 n=0 的情况。l[:len(l)-n]在一般情况下使用作品:

l=range(4)
for n in [2,1,0]: #test values for numbers of points to cut
    print n,l[:len(l)-n]

This is useful for example in a function to trim edges of a vector, where you want to leave the possibility not to cut anything.

例如,这在修剪向量边缘的函数中很有用,您希望保留不切割任何东西的可能性。

回答by Luca Citi

As Vincenzooo correctly says, the pythonic lst[:-n]does not work when n==0.

正如 Vincenzooo 正确说的那样,pythoniclst[:-n]n==0.

The following works for all n>=0:

以下适用于所有人n>=0

lst = lst[:-n or None]

I like this solution because it is kind of readable in English too: "return a slice omitting the last n elements or none (if none needs to be omitted)".

我喜欢这个解决方案,因为它在英语中也很可读:“返回一个省略最后 n 个元素或没有(如果不需要省略)的切片”。

This solution works because of the following:

此解决方案有效,原因如下:

  • x or yevaluates to xwhen xis logically true (e.g., when it is not 0, "", False, None, ...) and to yotherwise. So -n or Noneis -nwhen n!=0and Nonewhen n==0.
  • When slicing, Noneis equivalent to omitting the value, so lst[:None]is the same as lst[:](see here).
  • x or y评估x何时x逻辑上为真(例如,当它不是0, "", False, None, ...),y否则。所以,-n or None-n时候n!=0Nonen==0
  • 切片时,None相当于省略了值,所以lst[:None]lst[:](见这里)相同。

As noted by @swK, this solution creates a new list (but immediately discards the old one unless it's referenced elsewhere) rather than editing the original one. This is often not a problem in terms of performance as creating a new list in one go is often faster than removing one element at the time (unless n<<len(lst)). It is also often not a problem in terms of space as usually the members of the list take more space than the list itself (unless it's a list of small objects like bytesor the list has many duplicated entries). Please also note that this solution is not exactly equivalent to the OP's: if the original list is referenced by other variables, this solution will not modify (shorten) the other copiesunlike in the OP's code.

正如@swK 所指出的,此解决方案会创建一个新列表(但会立即丢弃旧列表,除非它在其他地方被引用),而不是编辑原始列表。就性能而言,这通常不是问题,因为一次性创建一个新列表通常比一次删除一个元素更快(除非n<< len(lst))。就空间而言,这通常也不是问题,因为通常列表的成员比列表本身占用更多的空间(除非它是一个小对象列表,bytes或者列表有许多重复的条目)。另请注意,此解决方案并不完全等同于 OP:如果原始列表被其他变量引用,则与 OP 代码不同,此解决方案不会修改(缩短)其他副本

A possible solution (in the same style as my original one) that works for n>=0but: a) does not create a copy of the list; and b) also affects other references to the same list, could be the following:

一种可能的解决方案(与我原来的风格相同)适用于n>=0:a)不创建列表的副本;b) 也会影响对同一列表的其他引用,可能如下:

    lst[-n:n and None] = []

This is definitely not readable and should not be used. Actually, even my original solution requires too much understanding of the language to be quickly read and univocally understood by everyone. I wouldn't use either in any real code and I think the best solution is that by @wonder.mice: a[len(a)-n:] = [].

这绝对不可读,不应使用。实际上,即使是我最初的解决方案,也需要对语言有太多的了解,才能让每个人都快速阅读并一目了然。我不会在任何实际代码中使用它们,我认为最好的解决方案是@wonder.mice: a[len(a)-n:] = []

回答by wonder.mice

Should be using this:

应该使用这个:

a[len(a)-n:] = []

or this:

或这个:

del a[len(a)-n:]

It's much faster, since it really removes items from existing array. The opposite (a = a[:len(a)-1]) creates new list object and less efficient.

它要快得多,因为它确实从现有数组中删除了项目。相反的 ( a = a[:len(a)-1]) 创建新的列表对象并且效率较低。

>>> timeit.timeit("a = a[:len(a)-1]\na.append(1)", setup="a=range(100)", number=10000000)
6.833014965057373
>>> timeit.timeit("a[len(a)-1:] = []\na.append(1)", setup="a=range(100)", number=10000000)
2.0737061500549316
>>> timeit.timeit("a[-1:] = []\na.append(1)", setup="a=range(100)", number=10000000)
1.507638931274414
>>> timeit.timeit("del a[-1:]\na.append(1)", setup="a=range(100)", number=10000000)
1.2029790878295898

If 0 < nyou can use a[-n:] = []or del a[-n:]which is even faster.

如果0 < n你可以使用a[-n:] = []或者del a[-n:]哪个更快。