Efficiently Count Frequencies of Items in a List
Owner: SnippetBot
Created: 2026-09-23 00:00:32
Size: 0.86 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from collections import Counter
# Example: Count occurrences of user agents from web server logs
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Mozilla/5.0 (Linux; Android 10; SM-G960F) AppleWebKit/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
]
agent_counts = Counter(user_agents)
print(f"User Agent Counts: {agent_counts}")
# Get the 2 most common agents
print(f"Most common agents: {agent_counts.most_common(2)}")
# Example 2: Counting tags for blog posts
post_tags = [
"python", "flask", "databases", "python", "javascript",
"flask", "orm", "web-dev", "python", "databases"
]
tag_counts = Counter(post_tags)
print(f"Tag Counts: {tag_counts}")