How should I handle inclusive ranges in Python?

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

    Without writing your own class, the function seems to be the way to go. What i can think of at most is not storing actual lists, just returning generators for the range you care about. Since we're now talking about usage syntax - here is what you could do

    def closed_range(slices):
        slice_parts = slices.split(':')
        [start, stop, step] = map(int, slice_parts)
        num = start
        if start <= stop and step > 0:
            while num <= stop:
                yield num
                num += step
        # if negative step
        elif step < 0:
            while num >= stop:
                yield num
                num += step
    

    And then use as:

    list(closed_range('1:5:2'))
    [1,3,5]
    

    Of course you'll need to also check for other forms of bad input if anyone else is going to use this function.

提交回复
热议问题