How should I handle inclusive ranges in Python?

后端 未结 12 2242
天涯浪人
天涯浪人 2020-12-14 05:56

I am working in a domain in which ranges are conventionally described inclusively. I have human-readable descriptions such as from A to B , which represent rang

12条回答
  •  情话喂你
    2020-12-14 06:11

    I believe that the standard answer is to just use +1 or -1 everywhere it is needed.

    You don't want to globally change the way slices are understood (that will break plenty of code), but another solution would be to build a class hierarchy for the objects for which you wish the slices to be inclusive. For example, for a list:

    class InclusiveList(list):
        def __getitem__(self, index):
            if isinstance(index, slice):
                start, stop, step = index.start, index.stop, index.step
                if index.stop is not None:
                    if index.step is None:
                        stop += 1
                    else:
                        if index.step >= 0:
                            stop += 1
                        else:
                            if stop == 0: 
                                stop = None # going from [4:0:-1] to [4::-1] since [4:-1:-1] wouldn't work 
                            else:
                                stop -= 1
                return super().__getitem__(slice(start, stop, step))
            else:
                return super().__getitem__(index)
    
    >>> a = InclusiveList([1, 2, 4, 8, 16, 32])
    >>> a
    [1, 2, 4, 8, 16, 32]
    >>> a[4]
    16
    >>> a[2:4]
    [4, 8, 16]
    >>> a[3:0:-1]
    [8, 4, 2, 1]
    >>> a[3::-1]
    [8, 4, 2, 1]
    >>> a[5:1:-2]
    [32, 8, 2]
    

    Of course, you want to do the same with __setitem__ and __delitem__.

    (I used a list but that works for any Sequence or MutableSequence.)

提交回复
热议问题