[Python] Finding the most common elements in an iterable

>>> import collections

>>> # Tally occurrences of words in a list
>>> cnt = collections.Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})


>>> c = collections.Counter('helloworld')

>>> c
Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})

>>> c.most_common(3)
[('l', 3), ('o', 2), ('e', 1)]

 https://docs.python.org/2/library/collections.html

原文地址:https://www.cnblogs.com/Answer1215/p/7999228.html