简体   繁体   中英

Python negative zero slicing

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.

Just use or 's coalescing behavior.

>>> print 4 or None
4
>>> print -3 or None
-3
>>> print -0 or None
None

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:]
[]

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[:]

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]
[]

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):]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM