본문 바로가기
Algorithm problem solving/기본

[python] collections.Counter

by Jiyoon-park 2020. 8. 23.

Collections.Counter()

A counter tool is provided to support convenient and rapid tallies. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

elements()

c = counter(a=4, b=2, c=0, d=-2)
sorted(c.elements())
// 결과값 ['a', 'a', 'a', 'a', 'b', 'b']

most_common(n)

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

Counter 끼리 빼고 더하는 것도 가능하다.

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d                      
// 결과값 Counter({'a': 4, 'b': 3})
c - d                       
// 결과값 Counter({'a': 2})

논리연산도 가능. 미쳤다.

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c & d                       
// 결과값 Counter({'a': 1, 'b': 1})
c | d                       
// 결과값 Counter({'a': 3, 'b': 2})

'Algorithm problem solving > 기본' 카테고리의 다른 글

python 자료구조_stack 과 queue  (0) 2020.08.29