Pythonβs collections module provides a rich set of data structures beyond the built-in ones. Among these, the Counter class is particularly useful for counting hashable objects. It functions similarly to a dictionary but is specifically designed to count occurrences of items. This document explores the Counter class in depth, including its initialization, usage patterns, built-in methods, arithmetic operations, advanced examples, and performance tips.
The Counter class is a subclass of the built-in dict class. It helps count hashable items efficiently and returns a dictionary-like object with elements as keys and counts as values.
from collections import Counter
from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
counter = Counter(colors)
print(counter)
text = "banana"
counter = Counter(text)
print(counter)
initial = {'apple': 3, 'orange': 2}
counter = Counter(initial)
print(counter)
counter = Counter(dog=3, cat=5)
print(counter)
counter = Counter("banana")
print(counter['a']) # Output: 3
print(counter['x']) # Output: 0 (non-existent keys return 0)
Returns an iterator over elements repeating as many times as their count:
counter = Counter(a=2, b=1)
print(list(counter.elements())) # ['a', 'a', 'b']
counter = Counter("mississippi")
print(counter.most_common(2)) # [('i', 4), ('s', 4)]
Updates counts from an iterable or mapping:
counter = Counter(a=1, b=2)
counter.update(a=3, b=1, c=2)
print(counter) # Counter({'a': 4, 'b': 3, 'c': 2})
counter.update("ababc")
print(counter)
Subtracts element counts from another iterable or mapping:
counter = Counter(a=4, b=2, c=3)
counter.subtract(a=1, b=3)
print(counter) # Counter({'c': 3, 'a': 3, 'b': -1})
c1 = Counter(a=2, b=1)
c2 = Counter(a=1, b=2)
print(c1 + c2) # Counter({'a': 3, 'b': 3})
print(c1 - c2) # Counter({'a': 1})
print(c1 & c2) # Counter({'a': 1, 'b': 1})
print(c1 | c2) # Counter({'a': 2, 'b': 2})
del counter['a']
print(counter)
counter.clear()
print(counter)
c1 = Counter(a=2, b=3)
c2 = Counter(a=2, b=2)
print(c1 == c2) # False
c3 = c1 + c2
print(c3) # Merges the counts
text = "this is a sample text with several words this is more words"
words = text.split()
counter = Counter(words)
print(counter.most_common(3))
sentence = "hello world"
char_counter = Counter(sentence.replace(" ", ""))
print(char_counter)
votes = ['Alice', 'Bob', 'Alice', 'Bob', 'Alice', 'Eve']
vote_count = Counter(votes)
print(vote_count.most_common(1))
import csv
from collections import Counter
with open("data.csv") as file:
reader = csv.reader(file)
fruits = [row[1] for row in reader]
counter = Counter(fruits)
print(counter)
counter = Counter("apple")
as_dict = dict(counter)
print(as_dict)
items = list(counter.items())
print(items)
numbers = [1, 2, 3, 2, 3, 4]
squared = map(lambda x: x ** 2, numbers)
counter = Counter(squared)
print(counter)
Although Counter is sufficient for counting, it can be combined with defaultdict for hierarchical data.
from collections import defaultdict, Counter
data = [('fruit', 'apple'), ('fruit', 'banana'), ('veggie', 'carrot'), ('fruit', 'apple')]
category_counter = defaultdict(Counter)
for category, item in data:
category_counter[category][item] += 1
print(category_counter)
# Dictionary approach
counts = {}
for item in ['a', 'b', 'a']:
counts[item] = counts.get(item, 0) + 1
# Counter approach
counter = Counter(['a', 'b', 'a'])
import matplotlib.pyplot as plt
data = "apple banana apple orange banana banana".split()
counter = Counter(data)
plt.bar(counter.keys(), counter.values())
plt.show()
log_entries = ["ERROR", "INFO", "WARNING", "ERROR", "INFO", "ERROR"]
log_counter = Counter(log_entries)
print(log_counter)
from bs4 import BeautifulSoup
from collections import Counter
html = "<html><body><div><p>Hello</p></div></body></html>"
soup = BeautifulSoup(html, 'html.parser')
tags = [tag.name for tag in soup.find_all()]
tag_counter = Counter(tags)
print(tag_counter)
The Counter class from Pythonβs collections module is a powerful and convenient tool for counting hashable objects. Whether you're analyzing text, processing data, or performing frequency analysis, Counter provides an efficient, readable, and feature-rich way to manage counts. With its rich set of built-in methods, support for arithmetic operations, and seamless integration with other Python modules, it is an indispensable utility for both beginner and advanced Python programmers. Understanding Counter can lead to cleaner, faster, and more Pythonic code for many common counting and frequency-based tasks.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved