파이썬 Counter 주요 메서드와 연산

개발공부를해보자·2025년 5월 15일

공부 정리

목록 보기
27/34

관련 문제: 프로그래머스 2018 KAKAO BLIND RECRUITMENT [1차] 뉴스 클러스터링

  • 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 값
profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글