Counter

LONGNEW·2021년 1월 25일
0

여러가지

목록 보기
14/18

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

딕셔너리의 서브 클래스로 hash 객체들을 카운트 하는 클래스이다.
아이템들이 딕셔너리의 key와 value 값으로 저장된다.

from collections import Counter

collections 라이브러리를 임포트 하거나, Counter 클래스를 따로 임포트 한다.

count 하려는 객체를 Counter 생성 할 때 parameter로 입력해준다.

c = Counter()                          
c = Counter('gallahad')                 
c = Counter({'red': 4, 'blue': 2})     
c = Counter(cats=4, dogs=8)  

그리고 입력 되지 않았던 값을 찾으려 할 경우엔 0을 리턴 한다.

c = Counter(['eggs', 'ham'])
c['bacon']                              # count of a missing element is zero
0

Counter에서 값을 제거 하려면 del 키워드를 이용해야 한다.

c['sausage'] = 0                       
del c['sausage']

그냥 count 횟수가 클수록 왼쪽에 저장 되는 것 같다.

그리고 3.7 버전이 되면서 순서를 저장할 수 있게 되었다.

elements()

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

입력 된 값들의 좌측부터 기록을 하며, 입력된 값이 count 된 횟수만큼 그 값을 리턴한다.
리턴할 때는 iterable 한 객체로 리턴 된다. 근데 진짜 iterable일 뿐..
sorted를 해줘야 위의 모양 처럼 나온다...
그리고 count 횟수가 1보다 작으면 무시한다.

most_common([n])

Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

n개의 가장 많이 count된 값들을 리스트로 리턴 한다. 만약 입력 값이 없다면 모든 아이템들을 리턴 한다. count가 동일 하다면 먼저 count된 값이 앞에 존재한다.

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)
c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

딕셔너리, 혹은 다른 값들을 뺀다. 차집합 느낌. 0이나 음수가 될 수도 있다.

여러 패턴들.

list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary

sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs

집합처럼 이용하기.

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

0개의 댓글