Identify groups of continuous numbers in a list

前端 未结 13 2171
误落风尘
误落风尘 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:45

    Here it is something that should work, without any import needed:

    def myfunc(lst):
        ret = []
        a = b = lst[0]                           # a and b are range's bounds
    
        for el in lst[1:]:
            if el == b+1: 
                b = el                           # range grows
            else:                                # range ended
                ret.append(a if a==b else (a,b)) # is a single or a range?
                a = b = el                       # let's start again with a single
        ret.append(a if a==b else (a,b))         # corner case for last single/range
        return ret
    

提交回复
热议问题