Python负零切片 [英] Python negative zero slicing
本文介绍了Python负零切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常发现自己必须处理序列中的最后n个项目,其中n可能为0.问题是尝试使用 [-n:]
进行切片无法 n == 0
的情况,因此需要笨拙的特殊情况代码.例如
I often find myself having to work with the last n items in a sequence, where n may be 0. The problem is that trying to slice with [-n:]
won't work in the case of n == 0
, so awkward special case code is required. For example
if len(b):
assert(isAssignableSeq(env, self.stack[-len(b):], b))
newstack = self.stack[:-len(b)] + a
else: #special code required if len=0 since slice[-0:] doesn't do what we want
newstack = self.stack + a
我的问题是-有没有办法在不需要笨拙的特殊大小写的情况下获得此行为?如果我不必一直检查0,那么代码会简单得多.
My question is - is there any way to get this behavior without requiring the awkward special casing? The code would be much simpler if I didn't have to check for 0 all the time.
推荐答案
您可以将其从 L [-2:]
切换为 L [len(L)-2:]
>>> L = [1,2,3,4,5]
>>> L[len(L)-2:]
[4, 5]
>>> L[len(L)-0:]
[]
这篇关于Python负零切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文