archive

[파이썬] collections.Counter 클래스 본문

STUDY/Python

[파이썬] collections.Counter 클래스

seonyounggg 2021. 2. 2. 22:48

collections 모듈의 Counter클래스는 컨테이너에 동일한 자료형이 몇 개인지 파악하는 데 사용하는 객체이다.

다음과 같이 import 해서 사용할 수 있다.

from collections import Counter

결과는 딕셔너리 형태로 반환된다.

Counter클래스의 다양한 예시는 아래와 같다.

 

- 리스트

import collections

words = ['a', 'a', 'b', 'c']
counts = collections.Counter(words)

print(counts)
'''
Counter({'a': 2, 'b': 1, 'c': 1})
'''

print(counts['a'])
'''
2
'''

print(counts['d'])
'''
0
'''

for key, value in counts.items():
    print(key, value)
'''
a 2
b 1
c 1
'''

print(counts.most_common(1))
'''
[('a', 2)]
'''

most_common()은 빈도수가 높은 순으로 상위 n개를 [('값', 개수)] 의 형태로 반환한다. n을 입력하지 않은 경우, 요소 전체에 대해 빈도수를 반환한다.

 

- 문자열

import collections

words = 'aabc'
# counts = collections.Counter(words) # 아래 두줄과 같은 의미
counts = collections.Counter()
counts.update(words)

print(counts)
'''
Counter({'a': 2, 'b': 1, 'c': 1})
'''

문자열도 리스트와 동일한 방식으로 사용할 수 있다.

update()는 Counter의 값을 갱신하는 것을 의미한다. 

 

- 딕셔너리

import collections

print(collections.Counter({'가': 3, '나': 2, '다': 4}))
'''
Counter({'다': 4, '가': 3, '나': 2})
'''

print(collections.Counter({'가': 'b', '나': 'a', '다': 'c'}))
'''
Counter({'다': 'c', '가': 'b', '나': 'a'})
'''

 value값 기준으로 정렬이 되는 것을 볼 수 있다.

아랫줄은 숫자가 아닌 경우도 되는지 궁금해서 해봤는데 되는 듯하다.

 

- 값=개수로 생성

# collections.Counter 예제 (3)
# '값=개수' 입력값으로 함
import collections
c = collections.Counter(a=2, b=3, c=2) # ['a', 'a', 'b', 'b', 'b', 'c', 'c']
print(collections.Counter(c))
print(sorted(c.elements()))
'''
결과
Counter({'b': 3, 'c': 2, 'a': 2})
['a', 'a', 'b', 'b', 'b', 'c', 'c']


출처: https://excelsior-cjh.tistory.com/94 [EXCELSIOR]

위와 같이 collections.Counter()에는 값=개수형태로 입력이 가능하다.

element()는 생성된 딕셔너리를 다시 리스트로 풀어서 반환한다.

 

'STUDY > Python' 카테고리의 다른 글

[Python] for-else, while-else  (0) 2021.02.19
[Python] any(), all() 함수  (0) 2021.02.18
파이썬 코딩 스타일 참고  (0) 2021.01.28
[파이썬] 리스트 컴프리헨션(List Comprehension)  (0) 2021.01.27
[파이썬] itertools모듈  (0) 2021.01.14
Comments