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

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

    To find unique elements in the list:

    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    a = list(set(a))
    

    To find the count of unique elements in a sorted array using dictionary:

    def CountFrequency(my_list): 
    # Creating an empty dictionary  
    freq = {} 
    for item in my_list: 
        if (item in freq): 
            freq[item] += 1
        else: 
            freq[item] = 1
    
    for key, value in freq.items(): 
        print ("% d : % d"%(key, value))
    
    # Driver function 
    if __name__ == "__main__":  
    my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] 
    
    CountFrequency(my_list)
    

    Reference:

    GeeksforGeeks

提交回复
热议问题