Identify groups of continuous numbers in a list

前端 未结 13 1910
误落风尘
误落风尘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 01:58

    Please note that the code using groupby doesn't work as given in Python 3 so use this.

    for k, g in groupby(enumerate(data), lambda x:x[0]-x[1]):
        group = list(map(itemgetter(1), g))
        ranges.append((group[0], group[-1]))
    

提交回复
热议问题