python - Counter

category python 2020. 12. 17. 23:12
728x90
반응형

정의

Counter 는 dict 해시 가능한 개체를 계산하기 위한 하위 클래스입니다. 요소가 사전 키로 저장되고 개수가 사전 값으로 저장되는 컬렉션입니다.

__init__ :  생성

  • 빈 객체로 생성
  • string 인자로 생성
  • dict 인자로 생성
  • keyword argument 인자로 생성
# 빈 객체로 생성
c = Counter() 

# string 인자로 생성
c = Counter('gallahad')

# dict 인자로 생성
c = Counter({'red': 4, 'blue': 2})

# keyword argument로 생성
c = Counter(cats=4, dogs=8)

# result
Counter()
Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
Counter({'red': 4, 'blue': 2})
Counter({'dogs': 8, 'cats': 4})

 

elements : 요소

개수만큼 반복되는 요소에 대해 반복을 합니다. 기준은 첫번째 검색된 순서대로입니다.

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

# result
['a', 'a', 'a', 'a', 'b', 'b']

 

most_common( [ n ] ) : 개수가 많은 요소

개수가 많은 요소들을 상위로하여 추출하여줍니다. 개수가 동일한 요소는 처음 발견 된 순서대로 정렬됩니다.

Counter('abracadabra').most_common(3)
Counter('abracadabra').most_common(2)

# result
[('a', 5), ('b', 2), ('r', 2)]
[('a', 5), ('b', 2)]

 

subtract( [ iterable-or-mapping ] )  : 뺄셈

이터레이터 또는 다른 매핑 (또는 카운터) 에서 요소를 뺍니다.

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

# result
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

 

수학적 연산

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)

# 덧셈 연산 
# add two counters together:  c[x] + d[x]
c + d                      
Counter({'a': 4, 'b': 3})

# 뺄셈 연산 (오직 빼는 주체가 + 인 경우만 키값을 유지합니다.
# subtract (keeping only positive counts)
c - d                       
Counter({'a': 2})

# 최소값으로 교차 연산합니다. 
# intersection:  min(c[x], d[x]) 
c & d              
Counter({'a': 1, 'b': 1})

# 교집합을 의미합니다.
# union:  max(c[x], d[x])
c | d              
Counter({'a': 3, 'b': 2})

 

출처 : https://docs.python.org/3/library/collections.html#collections.Counter

728x90
반응형

'python' 카테고리의 다른 글

python - 데코레이터 (Decorator)  (0) 2021.11.08
python - 힙 큐 (heapq)  (0) 2020.12.22
python - functools  (0) 2020.12.18
python - startswith, endswith  (0) 2020.12.18
python - Anaconda 설치  (0) 2018.01.22