List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abracadabra').most_common(3) [('a', 5), ('b', 2), ('r', 2)]
(self, n=None)
| 624 | return sum(self.values()) |
| 625 | |
| 626 | def most_common(self, n=None): |
| 627 | '''List the n most common elements and their counts from the most |
| 628 | common to the least. If n is None, then list all element counts. |
| 629 | |
| 630 | >>> Counter('abracadabra').most_common(3) |
| 631 | [('a', 5), ('b', 2), ('r', 2)] |
| 632 | |
| 633 | ''' |
| 634 | # Emulate Bag.sortedByCount from Smalltalk |
| 635 | if n is None: |
| 636 | return sorted(self.items(), key=_itemgetter(1), reverse=True) |
| 637 | |
| 638 | # Lazy import to speedup Python startup time |
| 639 | global heapq |
| 640 | if heapq is None: |
| 641 | import heapq |
| 642 | |
| 643 | return heapq.nlargest(n, self.items(), key=_itemgetter(1)) |
| 644 | |
| 645 | def elements(self): |
| 646 | '''Iterator over elements repeating each as many times as its count. |