Programming/Python

[Python] collections 모듈의 Counter 사용법

킹우현 2023. 10. 7. 03:20

1) Counter 기본 사용법

이번에는 데이터의 개수를 셀 때 매우 유용한 파이썬의 collections 모듈의 Counter 클래스에 대해서 알아보겠습니다.

from collections import Counter

collections 모듈의 Counter 클래스는 별도 패키지 설치 없이 파이썬만 설치되어 있다면 위와 같이 임포트해서 바로 사용할 수 있습니다.

>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})

>>> Counter("hello world")
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

Counter 생성자는 여러 형태의 데이터를 인자로 받는데요. 먼저 중복된 데이터가 저장된 배열을 인자로 넘기면 각 원소가 몇 번씩 나오는지가 저장된 객체를 얻게 됩니다.

 

counter = Counter("hello world")
counter["o"], counter["l"] # (2, 3)
counter["l"] += 1
counter["h"] -= 1
counter # Counter({'h': 0, 'e': 1, 'l': 4, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
if "o" in counter:
    print("o in counter")

del counter["o"]

if "o" not in counter:
    print("o not in counter")
    
# o in counter
# o not in counter

collections 모듈의 Counter 클래스는 파이썬의 기본 자료구조인 사전(dictionary)를 확장하고 있기 때문에, 사전에서 제공하는 API를 그대로 다 시용할 수가 있습니다.

 

2) 가장 흔한 데이터 찾기

from collections import Counter

Counter('hello world').most_common()

# [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]
from collections import Counter

Counter('hello world').most_common(1) # [('l', 3)]

아마도 실전에서 Counter가 자주 쓰이는 경우는 가장 많이 나온 데이터나 가장 적게 나온 데이터를 찾을 때일 것일 텐데요.

 

Counter 클래스는 이와 같은 작업을 좀 더 쉽게 할 수 있도록, 데이터의 개수가 많은 순으로 정렬된 배열을 리턴하는 most_common()이라는 메서드를 제공하고 있습니다.

 

3) 산술 연산자 활용

Counter가 재밌는 부분은 바로 마치 숫자처럼 산술 연산자를 사용할 수 있다는 것인데요. 예를 들어, 아래와 같이 2개의 카운터 객체가 있을 때,

counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])

counter1 + counter2 # Counter({'A': 3, 'B': 3})

counter1 - counter2 # Counter({'A': 1})

뺄셈의 결과로 0이나 음수가 나온 경우에는 최종 카운터 객체에서 제외가 되니 이 부분 주의해서 사용하시길 바랍니다.

 

참고 : https://www.daleseo.com/python-collections-counter/

 

파이썬 collections 모듈의 Counter 사용법

Engineering Blog by Dale Seo

www.daleseo.com