Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Efficient way to calculate Frequency of values in a Python list?

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.

like image 973
demos Avatar asked Jul 03 '10 17:07

demos


People also ask

How do you find the frequency of a string in a list Python?

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.

How do you count the frequency of a string in a list?

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.

How do you find the highest frequency in Python?

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.


1 Answers

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)]
like image 169
John La Rooy Avatar answered Oct 22 '22 23:10

John La Rooy