当 n 可能为零时,如何切片(在 Python 中)“除最后 n”之外的所有项目?

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

How to slice (in Python) "all but the last n" items when n may be zero?

pythonslice

提问by workerjoe

I have a list of items in Python and I need to get "all but the last N" items. It needs to work when N is zero (in which case I want the whole list) and when N is greater than or equal to the length of the list (in which case I want an empty list). This works in most cases:

我在 Python 中有一个项目列表,我需要获取“除最后 N 个之外的所有”项目。当 N 为零(在这种情况下我想要整个列表)并且当 N 大于或等于列表的长度(在这种情况下我想要一个空列表)时,它需要工作。这在大多数情况下有效:

mylist=[0,1,2,3,4,5,6,7,8,9]
print( mylist[:-n] )

But it fails in the case where N is zero. mylist[:0]returns an empty list: []. Is there a Python slicing notation that will do what I want, or a simple function?

但它在 N 为零的情况下失败。 mylist[:0]返回一个空列表:[]。是否有一个 Python 切片符号可以做我想要的,或者一个简单的函数?

采纳答案by John La Rooy

You can pass Noneto the slice

你可以传递None给切片

print(mylist[:-n or None])