728x90

Collections 모듈에서의 Counter 객체


Counter은 객체를 계산하기 위한 dict의 하위 클래스 입니다. 요소는 dictionary의 키로 저장되며 그들의 갯수는 dictionary의 value 값으로 저장되는 collection입니다. value 값은 0 또는 음수를 포함해 모둔 '정수' 값이 될 수 있습니다.

참고링크

 

 

Counter 선언방법


선언하는 방법은 2가지가 있습니다.

collections 모듈에서 Counter을 불러오는 방식입니다.

from collections import Counter # 방법 1

counter1 = Counter()

collections 모듈을 모두 불러와 collections를 접두사로 사용하는 방식입니다.

import collections # 방법 2

counter2 = collections.Counter()

밑에 설명하는 코드들은 방법 1을 사용해서 선언하도록 하겠습니다.

 

 

리스트(List) 와 카운터(Counter)


a = ['aaa','ddd','aaa','ccc','aaa','ccc','bbb','aaa']

counter = Counter(a)
print(counter)
>>> Counter({'aaa': 4, 'ccc': 2, 'ddd': 1, 'bbb': 1})

Counter의 type은 dict입니다.

list를 Counter를 통해 선언한다면, 반환하는 type은 Counter객체이지만 Counter 안에 있는 type은 dict입니다.

출력은 value값의 순서대로 출력합니다.(내림차순) 하지만 value가 같은 경우 key는 내림차순이 아닙니다.

딕셔너리(dictionary)와 카운터(Counter)


a = {'k': 5, 's': 1, 'c': 4}

counter = Counter(a)
print(counter)
>>> Counter({'k': 5, 'c': 4, 's': 1})

dict를 Counter을 통해 선언한다면 value값의 내림차순으로 출력합니다.하지만 value가 같은 경우 key는 내림차순이 아닙니다.

 

 

문자열(String)과 카운터(Counter)


a = 'aasdfasdf'

counter = Counter(a)
print(counter)
>>> Counter({'a': 3, 's': 2, 'd': 2, 'f': 2})

위와 다르게 이번엔 문자열(String)을 카운터(Counter)에 넣어서 반환하는 방식을 구현했습니다.

문자열별로 얼마나 count되었는지 확인할 수 있습니다.

 

숫자(integer)와 카운터(Counter)


a = 323124

counter = Counter(a)
print(counter)

Traceback (most recent call last):
  File "/Users/hwangiljeong/PycharmProjects/pythonProject/main.py", line 6, in <module>
    counter = Counter(a)
              ^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/collections/__init__.py", line 597, in __init__
    self.update(iterable, **kwds)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/collections/__init__.py", line 688, in update
    _count_elements(self, iterable)
TypeError: 'int' object is not iterable

정수는 오류가 not iterable 하기 때문에 오류가 발생합니다.

 

Counter의 함수들을 소개해보겠습니다.

 

element() 


c = Counter(a=4, b=2, c=0, d=-2)
print(sorted(c.elements())

>>> ['a', 'a', 'a', 'a', 'b', 'b']

개수만큼 반복되는 요소에 대한 이터레이터를 반환합니다. 요소는 처음 발견되는 순서대로 반환됩니다. 요소의 개수가 1보다 작으면 elements()는 이를 무시합니다.

 

most_common(n)


a = 'blogblogblogg'

counter = Counter(a)
print(counter.most_common())
>>> [('g', 4), ('b', 3), ('l', 3), ('o', 3)]

print(counter.most_common(2))
>>> [('g', 4), ('b', 3)]

n 개의 가장 흔한 요소와 그 개수를 가장 흔한 것부터 가장 적은 것 순으로 나열한 리스트를 반환합니다. 

n이 생략되거나 None이면, most_common()은 계수기의 모든 요소를 반환합니다. 개수가 같은 요소는 처음 발견된 순서를 유지합니다.

 

 

subtract()


c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
# c의 counter - d의 counter 

print(c)
>>> Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
# 각각의 요소를 뺀 값들을 출력

이터러블이나 다른 매핑 (또는 계수기)으로부터 온 요소들을 뺍니다. 입력과 출력 모두 0이나 음수일 수 있습니다.

 

Counter 활용방법


c = Counter('blogblogblogg')
c.total()                       # count의 총 개수
>>> 13

c = Counter('blogblogblogg')
c.clear()                       # 요소를 모두 제거
>>> None

c = Counter('blogblogblogg')
list(c)                         # 요소들을 list로 출렫하되 중복을 제거합니다.
>>> ['b', 'l', 'o', 'g']

c = Counter('blogblogblogg')
set(c)                          # set 형으로 변환합니다.
>>> {'b', 'o', 'g', 'l'}

c = Counter('blogblogblogg')
dict(c)                         # dictionary로 변환합니다.
>>> {'b': 3, 'l': 3, 'o': 3, 'g': 4}

c = Counter('blogblogblogg')
c.items()                       # (elem, cnt) 이러한 형태로 변환합니다.
>>> dict_items([('b', 3), ('l', 3), ('o', 3), ('g', 4)])

 

Counter 연산


c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
print(c + d)                       # add two counters together:  c[x] + d[x]
>>> Counter({'a': 4, 'b': 3})
print(c - d)                       # subtract (keeping only positive counts)
>>> Counter({'a': 2})
print(c & d)                       # intersection:  min(c[x], d[x])
>>> Counter({'a': 1, 'b': 1})
print(c | d)                       # union:  max(c[x], d[x])
>>> Counter({'a': 3, 'b': 2})
print(c == d)                      # equality:  c[x] == d[x]
>>> False
print(c <= d)                      # inclusion:  c[x] <= d[x]
>>> False
728x90