How should I handle inclusive ranges in Python?

后端 未结 12 2246
天涯浪人
天涯浪人 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:05

    Focusing on your request for best syntax, what about targeting:

    l[1:UpThrough(5):2]
    

    You can achieve this using the __index__ method:

    class UpThrough(object):
        def __init__(self, stop):
            self.stop = stop
    
        def __index__(self):
            return self.stop + 1
    
    class DownThrough(object):
        def __init__(self, stop):
            self.stop = stop
    
        def __index__(self):
            return self.stop - 1
    

    Now you don't even need a specialized list class (and don't need to modify global definition either):

    >>> l = [1,2,3,4]
    >>> l[1:UpThrough(2)]
    [2,3]
    

    If you use a lot you could use shorter names upIncl, downIncl or even In and InRev.

    You can also build out these classes so that, other than use in slice, they act like the actual index:

    def __int__(self):
        return self.stop
    

提交回复
热议问题