How can I find same values in a list and group together a new list?

后端 未结 6 1662
感情败类
感情败类 2020-12-03 07:11

From this list:

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

I\'m trying to create:

L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]
         


        
6条回答
  •  甜味超标
    2020-12-03 08:14

    You can do that using numpy too:

    import numpy as np
    
    N = np.array([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
    counter = np.arange(1, np.alen(N))
    L = np.split(N, counter[N[1:]!=N[:-1]])
    

    The advantage of this method is when you have another list which is related to N and you want to split it in the same way.

提交回复
热议问题