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

后端 未结 30 3243
时光说笑
时光说笑 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:09

    This answer is more explicit

    a = [1,1,1,1,2,2,2,2,3,3,3,4,4]
    
    d = {}
    for item in a:
        if item in d:
            d[item] = d.get(item)+1
        else:
            d[item] = 1
    
    for k,v in d.items():
        print(str(k)+':'+str(v))
    
    # output
    #1:4
    #2:4
    #3:3
    #4:2
    
    #remove dups
    d = set(a)
    print(d)
    #{1, 2, 3, 4}
    

提交回复
热议问题