Finding groups of increasing numbers in a list

前端 未结 8 2135
生来不讨喜
生来不讨喜 2021-01-05 03:37

The aim is to find groups of increasing/monotonic numbers given a list of integers. Each item in the resulting group must be of a +1 increment from the previous item

8条回答
  •  不知归路
    2021-01-05 04:21

    I think this works. It's not fancy but it's simple. It constructs a start list sl and an end list el, which should always be the same length, then uses them to index into x:

    def igroups(x):
        sl = [i for i in range(len(x)-1)
              if (x == 0 or x[i] != x[i-1]+1) and x[i+1] == x[i]+1]
    
        el = [i for i in range(1, len(x))
              if x[i] == x[i-1]+1 and (i == len(x)-1 or x[i+1] != x[i]+1)]
    
        return [x[sl[i]:el[i]+1] for i in range(len(sl))]
    

提交回复
热议问题