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

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

    Simple solution using a dictionary.

    def frequency(l):
         d = {}
         for i in l:
            if i in d.keys():
               d[i] += 1
            else:
               d[i] = 1
    
         for k, v in d.iteritems():
            if v ==max (d.values()):
               return k,d.keys()
    
    print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))
    

提交回复
热议问题