from collections import Counter
# Initial list with duplicate elements
logs = ["error", "info", "error", "warning", "error", "info"]
# 1. Instantly count the number of occurrences
count_dict = Counter(logs)
print(count_dict) # Counter({'error': 3, 'info': 2, 'warning': 1})
# 2. Get the most frequent elements (Top-2)
print(count_dict.most_common(2)) # [('error', 3), ('info', 2)]
# 3. Set math for counters
clicks_day1 = Counter(item=4, banner=2)
clicks_day2 = Counter(item=1, banner=5)
# Combine the results of two days in a single operation
print(clicks_day1 + clicks_day2) # Counter({'banner': 7, 'item': 5})
Forget about manual loops and dictionaries π«π
When you need to count the frequency of words in a text, the distribution of log types, or popular products in a store, developers usually create an empty dictionary and write a loop with a check if key not in dict: dict[key] = 1. The Counter class takes all this dirty work on itself and makes it as efficient as possible.
β Automatic initialization: You no longer need to check if a key exists in the dictionary. If the element is not there, Counter will not throw a KeyError, but simply return 0. π‘οΈ
β Finding leaders without sorting: The most_common(k) method returns a list of the k most frequently occurring elements. Under the hood, Python uses optimized heap algorithms, which work much faster than a full dictionary sort via sorted(). π
β Mathematical operations: You can add, subtract, intersect, and merge Counter objects. This turns them into a powerful tool for aggregating metrics and analytics from different data sources in a few lines of code. ββ
#Python #DataScience #Coding #Programming #Automation #DevOps
β¨ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk
βοΈ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
π Level up your AI & Data Science skills with HelloEncyclo β a growing all-in-one platform featuring hands-on courses in LLMs, Deep Learning, MLOps, Data Engineering, and more.
β 13 courses live + 40+ coming soon
π― One access, lifetime updates
π Use code: PRESALE-BOOK-WAVE-2GFG
π https://helloencyclo.com/?ref=HUSSEINSHEIKHO