본문 바로가기
파이썬(Python)/문법 내용정리

Collections 모듈 - Counter

by HealingMusic 2021. 1. 31.

파이썬의 collections 모듈은 데이터를 다루기 위한 유용한 컨테이너 객체를 지원한다. 알고리즘 공부를 하면서 이 collections 모듈을 자주 사용하는 관계로, 정리해 보기로 했다. Collections 모듈에는 Counter, Defaultdict, Orderdict(요즘은 의미가 거의 없지만), deque, namedtuple 등 여러 가지 데이터타입을 지원하는데, 여기서는 가장 많이 쓰이는 타입 중 하나인 Counter에 대해 알아보고자 한다. 추후 나머지 데이터타입들에 대해서도 유용한 것은 정리해볼 예정이다 (근데 그러면 글 순서는 어떻게 해야되지...?)

1. 객체 초기화

class collections.Counter([iterable-or-mapping])

Counter 객체는 dictionary의 일종으로, 파이썬의 내장 컨테이너(iterable이나 mapping, 즉 string, list, set, tuple이나 dict 등등) 들에 대해 원소의 개수와 관련된 정보를 저장한다. 따라서 iterable이나 mapping 객체를 인자로 하여 Counter 객체를 초기화할 수 있다.

 

아래 예시를 통해 여러 가지 방법으로 Counter 객체를 초기화해 보자. 우선 string을 이용한 방법이다.

from collections import Counter

string_ex = 'hello world from healingcoding!'

char_freq = Counter(string_ex) 
# string_ex 에서 각각의 char의 개수 정보를 리턴한다.

print(char_freq)

# result
Counter({'l': 4, 'o': 4, ' ': 3, 'h': 2, 'e': 2, 'r': 2, 'd': 2, 'i': 2, 'n': 2, 'g': 2, 'w': 1, 'f': 1, 'm': 1, 'a': 1, 'c': 1, '!' : 1})

위와 같이 char의 빈도수 정보를 가지는 Counter 객체가 초기화되었다. 이는 list나 set, dict에도 유사하게 적용된다 (set은 정의에 의해 모든 원소가 하나씩만 존재하겠지만, 여튼 기능은 적용된다)

 

list, dict의 경우는 다음과 같다.

from collections import Counter

list_ex = [1, 'abc'  , 3 , 2 , 3 , 4 , 3 , 'abc' , 'def' ]

list_freq = Counter(list_ex)
# string과 같은 방식으로 적용

print(list_freq) 
# result : Counter({3: 3, 'abc': 2, 1: 1, 2: 1, 4: 1, 'def': 1})


dict_ex = {'a' : 1, 'b' : 3, 'c' : 2, 'd' : 4}

dict_freq = Counter(dict_ex) 
# value 기준으로 내림차순 정렬됨. value가 int가 아닌 경우에는 적용되지 않음.

print(dict_freq) # result : Counter({'d': 4, 'b': 3, 'c': 2, 'a': 1})

위와 같이 적용된다. 이때 Counter의 인자로 dict를 사용하는 경우 단순히 Sorting된 형태로 초기화된다.

 

추가로 키 - 값을 직접 입력하는 방식으로도 Counter 객체 초기화가 가능하다.

from collections import Counter

count = Counter(a = 3, b = 2, d = 4, c = 1) 
# 'a'가 3번, 'b'가 2번, 'd'가 4번, 'c'가 1번

print(count)
# result : Counter({'d': 4, 'a': 3, 'b': 2, 'c': 1})

2. 메소드

most_common([n])

most_common이란 말 그대로 가장 많이 나온 원소와 횟수를 내림차순으로 list[tuple]의 형태로 리턴한다. 이때 정수 파라미터를 통해 리턴할 tuple의 개수를 지정할 수 있고, 입력하지 않으면 모두 포함해 리턴한다.

from collections import Counter

string_ex = 'hello world from healingcoding!'

char_freq = Counter(string_ex) 
# string_ex 에서 각각의 char의 개수 정보를 리턴한다.

print(char_freq.most_common(5)) 
# result : [('l', 4), ('o', 4), (' ', 3), ('h', 2), ('e', 2)]
elements()

Counter의 value들을 key만큼 반복하여 iterator로 리턴한다. 즉 Counter의 내용을 풀어서 리턴한다. 기본적으론는 빈도수 기준이나 key 기준으로 sorting이 되어 있지 않기 때문에, sorted 함수를 이용하여 list형태로 사용하는 것이 일반적이다. 

from collections import Counter

string_ex = 'hello world from healingcoding!'
char_freq = Counter(string_ex)

print(list(char_freq.elements())) 
# result : ['h', 'h', 'e', 'e', 'l', 'l', 'l', 'l', 'o', 'o', 'o', 'o', ' ', ' ', ' ', 'w', 'r', 'r', 'd', 'd', 'f', 'm', 'a', 'i', 'i', 'n', 'n', 'g', 'g', 'c', '!']

 

(이외에도 합집합, 차집합, update 등 여러 기능들이 있지만, 일단 많이 쓸 것 같은 기능들만 정리하였습니다)


레퍼런스

 

https://docs.python.org/3/library/collections.html

 

collections — Container datatypes — Python 3.9.1 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

https://velog.io/@misun9283/Python-collections-%EB%AA%A8%EB%93%88

 

Python -  collections.Counter 모듈

collections 이 모듈은 파이썬의 범용 내정 컨테이너 dict, list, set 및 tuple에 대한 대안을 제공하는 특수 컨테이너 데이터형을 구현합니다. collections.Counter() > Counter는 해시 가능한 객체를 세기 위한 di

velog.io

https://stackoverflow.com/questions/40950269/python-create-counter-from-mapping-non-integer-values

 

Python - Create Counter() from mapping, non-integer values

Consider a basic counter initialized from a mapping: dict_1 = {'a': 1, 'b': 2, 'c': 3} count_1 = Counter(dict_1) print count_1 >>> Counter({'c': 3, 'b': 2, 'a': 1}) Everything makes sen...

stackoverflow.com

 

'파이썬(Python) > 문법 내용정리' 카테고리의 다른 글

함수 인자 전달  (0) 2021.02.07
객체 in Python  (0) 2021.02.07
Type Hint (타입 힌트)  (0) 2021.01.29
Generator (제너레이터)  (0) 2021.01.28
F-string (가장 강력한 print 방법)  (0) 2021.01.28

댓글