collections.Counter เป็น subclass ของ dict สำหรับนับความถี่ (Frequency Counting) ใช้งานง่ายและทรงพลัง
การสร้าง Counter (3 วิธี)
import collections
# 1. จาก iterable
collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
# Counter({'b': 3, 'a': 2, 'c': 1})
# 2. จาก dict
collections.Counter({'a': 2, 'b': 3, 'c': 1})
# Counter({'b': 3, 'a': 2, 'c': 1})
# 3. จาก keyword arguments
collections.Counter(a=2, b=3, c=1)
# Counter({'b': 3, 'a': 2, 'c': 1})
Counter ว่าง และ update()
c = collections.Counter()
print(c) # Counter()
c.update('abcddcba')
print(c) # Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})
c.update({'a': 1, 'd': 5})
print(c) # Counter({'d': 7, 'a': 3, 'b': 2, 'c': 2})
เข้าถึงค่า
c = collections.Counter('abcddcba')
for letter in 'abcdef':
print(f'{letter}: {c[letter]}')
# a: 2, b: 2, c: 2, d: 2, e: 0, f: 0
# ไม่โยน KeyError สำหรับ key ที่ไม่มี (คืน 0)
print(c['z']) # 0
elements() และ most_common()
c = collections.Counter('Python Counters')
print(list(c.elements()))
# ['P', 'y', 't', 't', 'h', 'o', 'o', 'n', 'n', ' ', 'C', 'u', 'e', 'r', 's']
# Top 5 ตัวอักษรที่พบมากที่สุดในข้อความ
text = """Lorem ipsum dolor sit amet..."""
c = collections.Counter()
for word in text:
c.update(word.rstrip().lower())
for letter, count in c.most_common(5):
print(f'{letter}: {count}')
# i: 42, e: 38, t: 32, o: 29, u: 29
Arithmetic Operations
c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')
print(c1 + c2) # Combined counts
# Counter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
print(c1 - c2) # Subtraction (keep positive only)
# Counter({'b': 2, 'c': 1})
print(c1 & c2) # Intersection (min)
# Counter({'a': 2, 'b': 1})
print(c1 | c2) # Union (max)
# Counter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
Use Cases
- Frequency analysis (text, logs, DNA sequences)
- Multiset operations
- Anagram detection
- Most common items (top-K)