본문 바로가기
Python

[Python/파이썬] python collections - Counter()

by 댕댕미냉 2023. 1. 4.

Counter([iterable-or-mapping])

  • collections 모듈에 속한 클래스 중 하나인 Counter는 주로 해시 가능한 객체들을 셀 때 활용합니다.
  • 각 값들은 딕셔너리 형태로 저장되게 되는데, key 값은 element, value 값은 해당 element의 갯수를 의미합니다.

 

Counter 객체를 생성하는 방법

Counter 클래스를 쓰기 위해서는 먼저 collections 모듈에서 Counter를 import 해야 합니다.

Counter 객체를 생성하는 방법은 크게 4가지 방법이 있으며, 아래와 같습니다.

  • 빈 객체
  • iterable한 객체(문자열, range 등)
  • mapping된 객체(key-value)
  • keyword argument
from collections import Counter

c = Counter()

c1 = Counter('meinFigur')
# Counter({'i': 2, 'm': 1, 'e': 1, 'n': 1, 'F': 1, 'g': 1, 'u': 1, 'r': 1})

c2 = Counter({'red': 4, 'blue': 2})
# Counter({'red': 4, 'blue': 2})

c3 = Counter(dogs=8, cats=3)
# Counter({'dogs': 8, 'cats': 3})

 

Counter 특징

  • Counter는 value값에 0 또는 음수 값도 허용됩니다.
  • Counter는 생성 시 O(n)의 시간 복잡도를 가집니다.
  • Counter는 누락된 항목에 대해 KeyError가 발생하지 않고, 대신 0을 반환합니다.
c4 = Counter(a=1, b=3, c=19, d=5)
# Counter({'c': 19, 'd': 5, 'b': 3, 'a': 1})

c4['e']
# 0
  • 개수를 0으로 설정해도 key가 제거되지 않으므로, 완전히 제거하고자 한다면 del을 활용해서 제거할 수 있습니다.
c4['e'] = 0
del c4['e']

 

Counter Method

Counter는 dictionary의 서브클래스이므로, 일반적인 dictionary의 메서드를 활용할 수 있습니다.(단, fromKeysupdate는 예외)

  • fromKeys 의 경우, Counter에 구현되어 있지 않습니다.
  • update 의 경우, dictionary에서는 값을 교체하지만, Counter에서는 값을 더해주는 목적으로 사용합니다.
# dictionary

d = {'mein' : 4}
# {'mein': 4}

d.update({'mein': 10})
print(d) # {'mein': 10}


# Counter

c = Counter({'mein': 4})
# Counter({'mein': 4})

c.update({'mein': 10})
print(c) # Counter({'mein': 14})

 

dictionary의 메서드 이외에 추가로 지원되는 메서드는 다음과 같습니다.

  • elements() : 개수만큼 반복되는 key에 대한 iterator를 반환합니다. value의 값이 1보다 작으면 무시합니다.
c = Counter(d=2, a=3, c=0, b=2)
print(list(c.elements()))
# ['d', 'd', 'a', 'a', 'a', 'b', 'b']

 

  • most_common([n]) : value가 큰 key 부터 내림차순으로 n 개 만큼 반환합니다. n 이 생략되거나 None 이라면, 모든 key를 내림차순으로 반환합니다. value가 같은 key는 처음 순서를 유지합니다.
c = Counter(d=2, a=3, c=0, b=2)
print(c.most_common())
# [('a', 3), ('d', 2), ('b', 2), ('c', 0)]

print(c.most_common(1)) 
# [('a', 3)]

 

  • subtract([iterable or mapping]) : iterable이나 mapping으로부터 온 key의 value값을 뺍니다.
c = Counter(d=2, a=3, c=0, b=2)
it = {'a':2, 'b':3, 'c': 10, 'e':4, 'd':-1}
c.subtract(it)
print(c)
# Counter({'d': 3, 'a': 1, 'b': -1, 'e': -4, 'c': -10})

 

  • total() : 전체 개수(value의 합)을 계산하여 반환합니다.(python 3.10에서 추가된 메서드)
c = Counter(d=2, a=3, c=0, b=2)
print(c.total())
# 7

 

 

  • 위 게시글은 파이썬 공식 문서를 기반으로 작성되었습니다.

 

'Python' 카테고리의 다른 글

[Python/파이썬] python 내장함수 - zip()  (0) 2023.01.03