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

后端 未结 30 3236
时光说笑
时光说笑 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 03:12

    Here's another succint alternative using itertools.groupby which also works for unordered input:

    from itertools import groupby
    
    items = [5, 1, 1, 2, 2, 1, 1, 2, 2, 3, 4, 3, 5]
    
    results = {value: len(list(freq)) for value, freq in groupby(sorted(items))}
    

    results

    {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
    

提交回复
热议问题