问题
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
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.
回答1:
You can switch it from L[-2:]
to L[len(L)-2:]
>>> L = [1,2,3,4,5]
>>> L[len(L)-2:]
[4, 5]
>>> L[len(L)-0:]
[]
回答2:
Just use or
's coalescing behavior.
>>> print 4 or None
4
>>> print -3 or None
-3
>>> print -0 or None
None
回答3:
When you find yourself using a construct more than once, turn it into a function.
def last(alist, n):
if n:
return alist[:-n]
return alist
newstack = last(self.stack, len(b)) + a
An even simpler version as suggested by EOL in the comments:
def last(alist, n):
return alist[:-n] if n else alist[:]
回答4:
This is likely to be horribly inefficient, thanks to the double-reversing, but hopefully there's something to the idea of reversing the sequence to make the indexing easier:
a = [11, 7, 5, 8, 2, 6]
def get_last_n(seq, n):
back_seq = seq[::-1]
select = back_seq[:n]
return select[::-1]
print(get_last_n(a, 3))
print(get_last_n(a, 0))
Returns:
[8, 2, 6]
[]
回答5:
You can slip a conditional in there
L[-i if i else len(L):]
I think this version is less clear. You should use a comment along side it
L[-i or len(L):]
来源:https://stackoverflow.com/questions/11337941/python-negative-zero-slicing