converting a list of integers into range in python

后端 未结 11 1375
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 07:35

Is there something existing in python that can convert an increasing list of integers into a range list

E.g. given the set {0, 1, 2, 3, 4, 7, 8, 9, 11} I want to get

11条回答
  •  时光取名叫无心
    2020-11-28 08:08

    In the case there is no such feature in python, here is an implementation

    p = []
    last = -2                                                            
    start = -1
    
    for item in list:
        if item != last+1:                        
            if start != -1:
                p.append([start, last])
            start = item
        last = item
    
    p.append([start, last])
    

提交回复
热议问题