In Python's collections module, most_common() is a method of the Counter class that returns a list of the n most common elements and their counts in the Counter object. The elements are returned as a list of tuples in descending order of their count.
Here's an example of using the most_common() method in Python:
|
from collections import Counter
# Create a list of elements
elements = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
# Create a Counter object from the list
element_count = Counter(elements)
# Get the two most common elements and their counts
most_common = element_count.most_common(2)
# Print the most common elements and their counts
print(most_common)
|
Counter object from a list of elements and use the most_common() method to get the two most common elements and their counts. The output will look like this:
| [('apple', 3), ('banana', 2)] |
You can change the value of n to get a different number of most common elements. If n is not provided, most_common() returns all the elements and their counts in the Counter object.
|
from collections import Counter
# Create a string of characters
s = 'mississippi'
# Create a Counter object from the string
char_count = Counter(s)
# Get all the most common characters and their counts
most_common = char_count.most_common()
# Print the most common characters and their counts
print(most_common)
|
In this example, we create a Counter object from a string of characters and use the most_common() method without any argument to get all the most common characters and their counts. The output will look like this:
| [('i', 4), ('s', 4), ('p', 2), ('m', 1)] |
most_common() can be a useful tool when you need to analyze the most frequently occurring elements in a collection, such as words in a text or items in a sales report.