57. Python's collections.Counter
Here are 10 Python code snippets demonstrating the usage of Python's collections.Counter class to count occurrences of items in an iterable:
1. Basic Counting with Counter
Counting the occurrences of elements in a list.
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
counter = Counter(data)
print(counter)
# Output: Counter({'banana': 3, 'apple': 2, 'orange': 1})This snippet creates a Counter object to count occurrences of each item in the list data.
2. Counting Words in a Sentence
Counting the occurrences of words in a sentence.
from collections import Counter
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_count = Counter(words)
print(word_count)
# Output: Counter({'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1})This example counts the frequency of each word in the given sentence.
3. Counting Characters in a String
Counting the occurrences of characters in a string.
This counts the frequency of each character in the string text, including spaces.
4. Using Counter with a Dictionary
Converting a Counter object back into a dictionary.
This converts the Counter object into a dictionary, showing how the counts can be accessed.
5. Most Common Elements
Getting the most common elements from a Counter object.
This shows how to get the two most common elements and their counts from the Counter.
6. Subtracting Counts with Counter
Subtracting counts from a Counter object.
This demonstrates how to subtract the counts of one Counter object from another.
7. Adding Counts with Counter
Adding counts from two Counter objects.
This shows how to add counts from one Counter to another using the update() method.
8. Using Counter with Multiple Iterables
Counting occurrences across multiple iterables.
This demonstrates combining data from multiple iterables and counting their occurrences together.
9. Counting Elements in a Tuple
Using Counter with a tuple to count occurrences.
This counts the occurrences of each element in a tuple.
10. Handling Missing Keys with Counter
Using Counter to handle missing keys (defaults to 0).
This snippet shows that if you try to access a key that does not exist in the Counter, it will return 0 by default.
These code snippets demonstrate the versatility of the Counter class in the collections module, which makes it easy to count occurrences of items in iterables, handle default values, and perform arithmetic operations like adding and subtracting counts.
Last updated