How to do an inverse `range`, i.e. create a compact range based on a set of numbers?

前端 未结 6 651
忘了有多久
忘了有多久 2021-02-06 11:35

Python has a range method, which allows for stuff like:

>>> range(1, 6)
[1, 2, 3, 4, 5]

What I’m looking for is kind of t

6条回答
  •  爱一瞬间的悲伤
    2021-02-06 11:41

    Since 9000 beat me to it, I'll just post the second part of the code, that prints pcre-like ranges from the previously computed output plus the added type check:

    for i in output:
        if not isinstance(i, int) or i < 0:
            raise Exception("Only positive ints accepted in pcre_ranges")
    result = [ str(x[0]) if x[0] == x[1] else '%s-%s' % (x[0], x[1]) for x in output ]
    print result
    

    Output: ['1-3', '5-9', '20-23', '50']

提交回复
热议问题