How should I handle inclusive ranges in Python?

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

    Write an additional function for inclusive slice, and use that instead of slicing. While it would be possible to e.g. subclass list and implement a __getitem__ reacting to a slice object, I would advise against it, since your code will behave contrary to expectation for anyone but you — and probably to you, too, in a year.

    inclusive_slice could look like this:

    def inclusive_slice(myList, slice_from=None, slice_to=None, step=1):
        if slice_to is not None:
            slice_to += 1 if step > 0 else -1
        if slice_to == 0:
            slice_to = None
        return myList[slice_from:slice_to:step]
    

    What I would do personally, is just use the "complete" solution you mentioned (range(A, B + 1), l[A:B+1]) and comment well.

提交回复
热议问题