Identify groups of continuous numbers in a list

前端 未结 13 1939
误落风尘
误落风尘 2020-11-22 01:12

I\'d like to identify groups of continuous numbers in a list, so that:

myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])

Returns:

         


        
13条回答
  •  误落风尘
    2020-11-22 01:58

    Using groupby and count from itertools gives us a short solution. The idea is that, in an increasing sequence, the difference between the index and the value will remain the same.

    In order to keep track of the index, we can use an itertools.count, which makes the code cleaner as using enumerate:

    from itertools import groupby, count
    
    def intervals(data):
        out = []
        counter = count()
    
        for key, group in groupby(data, key = lambda x: x-next(counter)):
            block = list(group)
            out.append([block[0], block[-1]])
        return out
    

    Some sample output:

    print(intervals([0, 1, 3, 4, 6]))
    # [[0, 1], [3, 4], [6, 6]]
    
    print(intervals([2, 3, 4, 5]))
    # [[2, 5]]
    

提交回复
热议问题