How should I handle inclusive ranges in Python?

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

    Instead of creating API that is not conventional or extending data types like list, it would be ideal to create a Slice function a wrapper over the built-in slice so that you can pass it across any where, a slicing is requiring. Python has support for this approach for some exceptional cases, and the case you have could warrant for that exception case. As an example, an inclusive slice would look like

    def islice(start, stop = None, step = None):
        if stop is not None: stop += 1
        if stop == 0: stop = None
        return slice(start, stop, step)
    

    And you can use it for any sequence types

    >>> range(1,10)[islice(1,5)]
    [2, 3, 4, 5, 6]
    >>> "Hello World"[islice(0,5,2)]
    'Hlo'
    >>> (3,1,4,1,5,9,2,6)[islice(1,-2)]
    (1, 4, 1, 5, 9, 2)
    

    Finally you can also create an inclusive range called irange to complement the inclusive slice (written in lines of OPs).

    def irange(start, stop, step):
        return range(start, (stop + 1) if step >= 0 else (stop - 1), step)
    

提交回复
热议问题