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

前端 未结 6 641
忘了有多久
忘了有多久 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 12:00

    Sort numbers, find consecutive ranges (remember RLE compression?).

    Something like this:

    input = [5,7,9,8,6, 21,20, 3,2,1, 22,23, 50]
    
    output = []
    first = last = None # first and last number of current consecutive range
    for item in sorted(input):
      if first is None:
        first = last = item # bootstrap
      elif item == last + 1: # consecutive
        last = item # extend the range
      else: # not consecutive
        output.append((first, last)) # pack up the range
        first = last = item
    # the last range ended by iteration end
    output.append((first, last))
    
    print output
    

    Result: [(1, 3), (5, 9), (20, 23), (50, 50)]. You figure out the rest :)

提交回复
热议问题