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

后端 未结 30 2875
时光说笑
时光说笑 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
    num=[3,2,3,5,5,3,7,6,4,6,7,2]
    print ('\nelements are:\t',num)
    count_dict={}
    for elements in num:
        count_dict[elements]=num.count(elements)
    print ('\nfrequency:\t',count_dict)
    
    0 讨论(0)
  • 2020-11-22 03:09

    Data. Let's say we have a list:

    fruits = ['banana', 'banana', 'apple', 'banana']
    

    Solution. Then we can find out how many of each fruit we have in the list by doing this:

    import numpy as np    
    (unique, counts) = np.unique(fruits, return_counts=True)
    {x:y for x,y in zip(unique, counts)}
    

    Output:

    {'banana': 3, 'apple': 1}
    
    0 讨论(0)
  • 2020-11-22 03:10
    def frequencyDistribution(data):
        return {i: data.count(i) for i in data}   
    
    print frequencyDistribution([1,2,3,4])
    

    ...

     {1: 1, 2: 1, 3: 1, 4: 1}   # originalNumber: count
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 2020-11-22 03:12
    from collections import Counter
    a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]
    
    counter=Counter(a)
    
    kk=[list(counter.keys()),list(counter.values())]
    
    pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])
    
    0 讨论(0)
  • 2020-11-22 03:12

    For your first question, iterate the list and use a dictionary to keep track of an elements existsence.

    For your second question, just use the set operator.

    0 讨论(0)
提交回复
热议问题