I am looking for a fast and efficient way to calculate the frequency of list
items in python:
list = ['a','b','a','b', ......]
I want a frequency counter which would give me an output like this:
[ ('a', 10),('b', 8) ...]
The items should be arranged in descending order of frequency as shown above.
Use set() method to remove a duplicate and to give a set of unique words. Iterate over the set and use count function (i.e. string. count(newstring[iteration])) to find the frequency of word at each iteration.
We can use the counter() method from the collections module to count the frequency of elements in a list. The counter() method takes an iterable object as an input argument. It returns a Counter object which stores the frequency of all the elements in the form of key-value pairs.
Mode denoted the maximum frequency element in mathematics and python dedicates a whole library to statistical function and this can also be used to achieve this task. The lesser known method to achieve this particular task, Counter() uses the most_common function to achieve this in one line.
Python2.7+
>>> from collections import Counter
>>> L=['a','b','a','b']
>>> print(Counter(L))
Counter({'a': 2, 'b': 2})
>>> print(Counter(L).items())
dict_items([('a', 2), ('b', 2)])
python2.5/2.6
>>> from collections import defaultdict
>>> L=['a','b','a','b']
>>> d=defaultdict(int)
>>> for item in L:
>>> d[item]+=1
>>>
>>> print d
defaultdict(<type 'int'>, {'a': 2, 'b': 2})
>>> print d.items()
[('a', 2), ('b', 2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With