Language/Python

[Python] collections모듈 Counter 사용하기

Deveun 2021. 7. 4. 00:43

(python ver.3.9.6 기준)

 

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

: 리스트의 원소들이 각각 몇 개 씩 존재하는지 카운팅하는 클래스

파라미터로는 *iterable / mapping (keyword = count, { "key" : "count"}) 같은 타입이 쓰인다. 

 

*iterable

: 멤버값을 하나씩 return 할 수 있는 오브젝트로 for loop나 zip(), map() 등에서 쓰일 수 있다.

list, str, tuple 등(sequence type) / dict, file object 등 (non-sequence type)이 이 포함된다.

 

 

- Counter 생성 예

from collections import Counter

c = Counter('hello')
# String 파라미터 >>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
c = Counter({'a':3, 'b':2, 'c':7})
# map 파라미터 >>> Counter({'c': 7, 'a': 3, 'b': 2})
c = Counter(a=3, b=5)
# keyword args 파라미터 >>> Counter({'b': 5, 'a': 3})

 

 

[주요함수]

o elements()

: 각각의 요소를 count만큼 반복한 iterator를 반환

o most_common([n])

: n개의 가장 많은 count 요소를 ('value', count)의 리스트로 반환

o subtract([iterable-or-mapping])

: a.subtract(b) 의 경우 a Counter에서 b Counter 값을 뺌

...

 

 

- Counter 사용 예

from collections import Counter

c = Counter('aabcac')

print(c['a'], c['b'], c['c']) # >>> 3 1 2
print(c['d']) # >>> 0
print(sorted(c.elements())) # >>> ['a', 'a', 'a', 'b', 'c', 'c']
print(c.most_common(2)) # >>> [('a', 3), ('c', 2)]

d = Counter('abab')
print(c + d) # >>> Counter({'a':5, 'b':3, 'c':2}
print(c - d) # >>> Counter({'c': 2, 'a': 1}) # 양수값만 출력
c.subtract(d)
print(c) # >>> Counter({'c': 2, 'a': 1, 'b': -1})

 

 

[참고] https://docs.python.org/3/library/collections.html#collections.Counter

 

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