Counter is a built-in class in Python's collections module that is used to count the occurrences of elements in an iterable object. It is a dictionary subclass that takes an iterable object as input and returns a dictionary with elements as keys and their frequency as values.
Here's an example of using the Counter class 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)
# Print the frequency of each element
print(element_count)
|
In this example, we create a list of elements and then create a Counter object from the list. We then print the element_count dictionary, which shows the frequency of each element in the list. The output will look like this:
| Counter({'apple': 3, 'banana': 2, 'cherry': 1}) |
Counter object can also be created from other iterable objects like strings, tuples, or even another dictionary. The most_common() method can be used to retrieve the most frequently occurring elements and their counts as a list of tuples.
|
from collections import Counter
# Create a string of characters
s = 'mississippi'
# Create a Counter object from the string
char_count = Counter(s)
# Print the most common characters and their counts
print(char_count.most_common(3))
|
Counter object from a string of characters and use the most_common() method to print the three most frequently occurring characters and their counts. The output will look like this:
| [('i', 4), ('s', 4), ('p', 2)] |
Counter can be a useful tool in data analysis and manipulation tasks where you need to count the frequency of items in a collection.