Python @ DjangoSpin

Python: Retrieving Most Frequent Elements in an Iterable

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Retrieving Most Frequent Elements in an Iterable in Python

Retrieving Most Frequent Elements in an Iterable in Python

The Counter class of builtin module collections creates a dictionary of all elements of a given iterable object, along with corresponding number of occurrences. It provides a few useful methods, one of which is most_common(). This method takes an integer input, say n, and provides a list of tuples of n most common elements with their corresponding number of occurrences.

import collections

words = [
    '!', '@', '#', '$', '%',
    '@', '#', '$', '%',
    '#', '$', '%',
    '$', '%',
     '%',
]

characterCounts = collections.Counter(words)
threeMostFrequentCharacters = characterCounts.most_common(3)
print(threeMostFrequentCharacters)              # [('%', 5), ('$', 4), ('#', 3)]

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply