How to slice (in Python) “all but the last n” items when n may be zero? [duplicate]

試著忘記壹切 提交于 2019-12-08 14:54:25

问题


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:

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?


回答1:


You can pass None to the slice

print(mylist[:-n or None])


来源:https://stackoverflow.com/questions/30765493/how-to-slice-in-python-all-but-the-last-n-items-when-n-may-be-zero

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!