공부/Python

[Python] Counter 클래스

Jii- 2024. 1. 23. 17:44

collections 모듈

Counter 클래스는 collections 모듈의 클래스 중 하나이다. collections 모듈은 파이썬의 내장 컨테이너 dict, list, set 및 tuple에 대한 대안을 제공하는 특수 컨테이너 데이터형을 구현한다.

namedtuple() 이름 붙은 필드를 갖는 튜플 서브 클래스를 만들기 위한 팩토리 함수
deque 양쪽 끝에서 빠르게 추가와 삭제를 할 수 있는 리스트류 컨테이너
ChainMap 여러 매핑의 단일 뷰를 만드는 딕셔너리류 클래스
Counter 해시 가능한 객체를 세는 데 사용되는 딕셔너리 서브 클래스
OrderedDict 항목이 추가된 순서를 기억하는 딕셔너리 서브 크래스
defaultdict 누락된 값을 제공하기 위해 팩토리 함수를 호출하는 딕셔너리 서브 클래스
UserDict 더 쉬운 딕셔너리 서브 클래싱을 위해 딕셔너리 객체를 감싸는 래퍼
UserList 더 쉬운 서브 클래싱을 위해 리스트 객체를 감싸는 래퍼
UserString 더 쉬운 문자열 서브 클래싱을 위해 문자열 객체를 감싸는 래퍼

 

collections 모듈의 Counter 클래스

Counter 클래스는 컨테이너 안의 데이터 개수를 세주는 도구이다. Counter 객체는 주어진 리스트의 각 요소를 키(Key)로, 해당 요소의 개수를 값(Value)으로 갖는다. 아래 예시 코드를 통해 확인할 수 있다. 

from collections import Counter

fruit_list = ['banana', 'apple', 'strawberry', 'strawberry', 'banana', 'blueberry']
fruit_counter = Counter(fruit_list)

print(fruit_counter)

"""
출력 결과 : 
Counter({'banana': 2, 'strawberry': 2, 'apple': 1, 'blueberry': 1})
"""

 

Counter 클래스는 리스트 외에도 문자열의 문자 개수도 계산할 수 있다. 이 경우에 Counter 객체는 문자열의 각 문자를 키(Key)로, 해당 요소의 개수를 값(Value)으로 갖는다. 아래 예시 코드를 통해 확인할 수 있다. 

from collections import Counter

banana_counter = Counter()
banana_counter.update('banana')
print(banana_counter)

"""
출력 결과:
Counter({'a': 3, 'n': 2, 'b': 1})
"""

 

딕셔너리 역시 Counter를 사용할 수 있다. 

from collections import Counter

fruit_dic = {'banana' : 2, 'apple' : 10, 'blueberry' : 1, 'strawberry' : 5}
fruit_counter = Counter(fruit_dic)
print(fruit_counter)

"""
출력 결과:
Counter({'apple': 10, 'strawberry': 5, 'banana': 2, 'blueberry': 1})
"""

 

위의 예시들을 통해 알 수 있듯이, Counter 클래스는 요소의 개수가 많은 것부터 출력한다. 

 

Counter 클래스의 산술/집합 연산

1. 덧셈 연산

from collections import Counter

fruit_counter1 = Counter(['banana', 'blueberry', 'banana', 'watermelon'])
fruit_counter2 = Counter(['strawberry', 'banana', 'apple'])

print(fruit_counter1 + fruit_counter2)

"""
출력 결과:
Counter({'banana': 3, 'blueberry': 1, 'watermelon': 1, 'strawberry': 1, 'apple': 1})
"""

 

2. 뺄셈 연산

from collections import Counter

fruit_counter1 = Counter(['banana', 'blueberry', 'banana', 'watermelon'])
fruit_counter2 = Counter(['strawberry', 'banana', 'apple'])

print(fruit_counter1 - fruit_counter2)

"""
출력 결과:
Counter({'banana': 1, 'blueberry': 1, 'watermelon': 1})
"""

 

3. 교집합 연산

from collections import Counter

fruit_counter1 = Counter(['banana', 'blueberry', 'banana', 'watermelon'])
fruit_counter2 = Counter(['strawberry', 'banana', 'apple'])

print(fruit_counter1 & fruit_counter2)

"""
출력 결과:
Counter({'banana': 1})
"""

 

3. 합집합 연산

from collections import Counter

fruit_counter1 = Counter(['banana', 'blueberry', 'banana', 'watermelon'])
fruit_counter2 = Counter(['strawberry', 'banana', 'apple'])

print(fruit_counter1 | fruit_counter2)

"""
출력 결과:
Counter({'banana': 2, 'blueberry': 1, 'watermelon': 1, 'strawberry': 1, 'apple': 1})
"""

 

Counter 클래스의 메소드

1. elements() 

Counter 객체의 요소를 개수만큼 반복하여 반환하는 메소드이다. 

from collections import Counter

fruit_counter = Counter({'banana' : 2, 'apple' : 1, 'blueberry' : 0, 'strawberry' : 3})
sorted(fruit_counter.elements())

"""
출력 결과:
['apple', 'banana', 'banana', 'strawberry', 'strawberry', 'strawberry']
"""

 

2. most_common([n]) 

Counter 객체의 요소 중 값이 가장 큰 n개를 반환하는 메소드이다. 만약 매개변수가 없다면 요소 전체를 반환하는 것이 특징이다. 

from collections import Counter

fruit_counter = Counter({'banana' : 2, 'apple' : 1, 'blueberry' : 0, 'strawberry' : 3})

print(fruit_counter.most_common(2))
print(fruit_counter.most_common())

"""
출력 결과:
[('strawberry', 3), ('banana', 2)]
[('strawberry', 3), ('banana', 2), ('apple', 1), ('blueberry', 0)]
"""

 

3. subtract()

뺄셈 연산과 유사한 메소드이지만 음수 값이 반환된다는 것이 특징이다. 

from collections import Counter

fruit_counter1 = Counter(['banana', 'blueberry', 'banana', 'watermelon'])
fruit_counter2 = Counter(['strawberry', 'banana', 'apple', 'blueberry', 'blueberry'])

fruit_counter1.subtract(fruit_counter2)
print(fruit_counter1)

"""
출력 결과:
Counter({'banana': 1, 'watermelon': 1, 'blueberry': -1, 'strawberry': -1, 'apple': -1})
"""

 

4. total()

Counter 객체 요소의 총합을 반환하는 메소드이다. 

from collections import Counter

fruit_counter = Counter({'banana' : 2, 'apple' : 1, 'blueberry' : 0, 'strawberry' : 3})

print(fruit_counter.total())

"""
출력 결과:
6
"""