有没有更好的方法来删除列表的最后 N 个元素。
for i in range(0,n):
lst.pop( )
效劳于n >= 1
>>> L = [1,2,3, 4, 5]
>>> n=2
>>> del L[-n:]
>>> L
[1, 2, 3]
如果您希望删除最后 n 个元素,换句话说,保留第一个 len - n 个元素:
lst = lst[:len(lst)-n]
注意:这不是内存操作。它会创建一个浅拷贝。
正如 Vincenzooo 正确所说,pythoniclst[:-n]
在n==0
.
以下适用于所有人n>=0
:
lst = lst[:-n or None]
我喜欢这个解决方案,因为它在英语中也具有可读性:“返回一个省略最后 n 个元素的切片,或者没有(如果不需要省略)”。
由于以下原因,此解决方案有效:
x or y
评估x
何时x
逻辑上为真(例如,当它不是0
, ""
, False
, None
, ... 时),y
否则。何时何地-n or None
也是如此。-n
n!=0
None
n==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 bytes
or 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 copies unlike in the OP's code.
A possible solution (in the same style as my original one) that works for n>=0
but: a) does not create a copy of the list; and b) also affects other references to the same list, could be the following:
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:] = []
.
试着像这样删除它。
del list[-n:]
我看到这是很久以前问过的,但没有一个答案适合我;如果我们想得到一个没有最后 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]
就如此容易。
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.
>>> 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 < n
you can use a[-n:] = []
or del a[-n:]
which is even faster.
这是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]
例如,这在修剪矢量边缘的函数中很有用,您希望保留不剪切任何东西的可能性。