collections.Counter() is a built-in Python class that provides a convenient way to count the occurrences of elements in a sequence or container. It takes an iterable object as input and returns a dictionary-like object with the elements of the iterable as keys and their counts as values.
Here's an example of how to use collections.Counter() to count the occurrences of words in a list of strings:
from collections import Counterwords = ['apple', 'banana', 'orange', 'apple', 'kiwi', 'banana']word_counts = Counter(words)print(word_counts) |
Output:
Counter({'apple': 2, 'banana': 2, 'orange': 1, 'kiwi': 1}) |
In this example, we first import the Counter class from the collections module. We then create a list of strings words containing some fruit names. We pass words as input to Counter() to get a Counter object word_counts, which contains the counts of each word in words.
You can access the count of a specific element in the Counter object using square bracket notation with the element as the key. For example:
print(word_counts['apple']) # Output: 2 |
collections.Counter() is a useful tool for quickly and efficiently counting the occurrences of elements in a sequence or container, and can be especially useful for large datasets where other methods might be slower or more memory-intensive.