-1

Consider a list with 100 elements. I want to write a code to print 10 most occuring element.

import itertools
import operator

def most_common(lst):
    return max(set(lst), key=lst.count)

THis is giving me the 1st most occuring element. I want 10 most occuring.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Joe
  • 1

1 Answers1

2

For calculating frequencies of hashable objects, Counter is great in python:

from collections import Counter

my_list = ['a','b','c','a','a','b','c','a','a','a','a','a','a','a','a','b','c','b','c','b','c','d','d','d','d','d']

freqs= Counter(my_list)
print(freqs.most_common(3))

Output

[('a', 11), ('b', 5), ('c', 5)]

In your case, you would substitute 3 in the parameters of most_common() function with the desired number of elements, which is 10.