Identify groups of continuous numbers in a list

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

    import numpy as np
    
    myarray = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
    sequences = np.split(myarray, np.array(np.where(np.diff(myarray) > 1)[0]) + 1)
    l = []
    for s in sequences:
        if len(s) > 1:
            l.append((np.min(s), np.max(s)))
        else:
            l.append(s[0])
    print(l)
    

    Output:

    [(2, 5), (12, 17), 20]
    

提交回复
热议问题