How to count the frequency of the elements in an unordered list?

后端 未结 30 3265
时光说笑
时光说笑 2020-11-22 02:37

I need to find the frequency of elements in an unordered list

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

output->

b =         


        
30条回答
  •  故里飘歌
    2020-11-22 02:55

    Note: You should sort the list before using groupby.

    You can use groupby from itertools package if the list is an ordered list.

    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    from itertools import groupby
    [len(list(group)) for key, group in groupby(a)]
    

    Output:

    [4, 4, 2, 1, 2]
    

提交回复
热议问题