Counter()를 자주 사용하는데 그 연산은 자주 사용하지 않아 익숙하지 않았다.from collections import Counter
# 데이터 준비
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
# 1. most_common() - 가장 많이 등장한 항목을 내림차순으로 반환
c = Counter(words)
print(c.most_common(2)) # [('apple', 3), ('banana', 2)]
# 2. update() - 기존 Counter에 요소 추가 (개수 증가)
c.update(['banana', 'grape'])
print(c) # Counter({'apple': 3, 'banana': 3, 'orange': 1, 'grape': 1})
# 3. elements() - 등장 횟수만큼 요소 반복 (0 이하 제외), 반환값은 iterator
print(list(c.elements()))
# ['apple', 'apple', 'apple', 'banana', 'banana', 'banana', 'orange', 'grape']
# 4. subtract() - 특정 요소의 개수 빼기 (음수 허용)
c.subtract({'apple': 2, 'banana': 5})
print(c) # Counter({'apple': 1, 'orange': 1, 'grape': 1, 'banana': -2})
# 5. 산술/집합 연산
c1 = Counter('aabbc')
c2 = Counter('bccdd')
print(c1 + c2) # Counter({'b': 3, 'c': 2, 'a': 2, 'd': 2})
print(c1 - c2) # Counter({'a': 2, 'b': 1}) → c, d는 음수 되어 제거됨
print(c1 & c2) # Counter({'b': 1, 'c': 1}) → 각 value의 min 값
print(c1 | c2) # Counter({'b': 2, 'c': 2, 'a': 2, 'd': 2}) → 각 value의 max 값