Kim Jinung

Python - Counter 본문

Language/Python

Python - Counter

Kim Jinung 2022. 12. 6. 16:28
 

collections — Container datatypes — Python 3.11.0 documentation

collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f

docs.python.org

Counter 클래스는 Dictionary의 subclass로 hashable한 객체를 카운팅할 때 사용할 수 있다.


 

특정 요소가 몇번 등장하는지 저장하기 위해서 Dictionary를 사용하는 경우, 아래와 같은 패턴을 자주 사용해왔다. 

 

1. numbers는 숫자로만 구성된 리스트다.

2. numbers 리스트에 등장하는 각 요소들이 몇번 등장하는지 저장하기 위해서 num_dict에 카운팅한다.

numbers = [1, 1, 2, 3, 3]

num_dict = {}

for num in numbers:
	if num_dict.get(num) is not None:
    	num_dict[num] += 1
    else:
    	num_dict[num] = 1

 

 

collections 모듈의 Counter 클래스는 Dictionary의 subclass로 위 작업을 해준다. 소스 코드를 뜯어 보면, 위에서 다룬 숫자 형태 뿐만 아니라 문자열에 등장하는 알파벳의 경우도 카운팅해주는 것을 확인할 수 있다.

 

 

처음에 다룬 예시를 Counter 클래스를 이용해서 표현하면 다음과 같이 간단하게 처리할 수 있다.

from collections import Counter

numbers = [1, 1, 2, 3, 3]

counter = Counter(numbers)

 

'Language > Python' 카테고리의 다른 글

Python - functools.cmp_to_key (compare sort, 비교 정렬)  (0) 2023.01.19
Python - heapq  (0) 2022.12.08
Python - for/else  (0) 2022.12.02
Python - Regular Expression  (0) 2022.11.30
Python - GIL(Global Interpreter Lock)  (0) 2022.11.23