Identify groups of continuous numbers in a list

前端 未结 13 1924
误落风尘
误落风尘 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 02:03

    Assuming your list is sorted:

    >>> from itertools import groupby
    >>> def ranges(lst):
        pos = (j - i for i, j in enumerate(lst))
        t = 0
        for i, els in groupby(pos):
            l = len(list(els))
            el = lst[t]
            t += l
            yield range(el, el+l)
    
    
    >>> lst = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17]
    >>> list(ranges(lst))
    [range(2, 6), range(12, 18)]
    
    0 讨论(0)
提交回复
热议问题