파이썬 스터디

collections - Counter

0_TLS 2023. 8. 15. 20:19

파이썬에 기본적으로 내장되어 있는 collections모듈의 Counter클래스를 이용하면 데이터의 개수를 쉽게 셀 수 있음.

from collections import Counter

데이터와 개수가 딕셔너리 형태로 출력됨.

>>> from collections import Counter
>>> Counter(['A', 'B', 'A+', 'B+', 'A+', 'A'])
Counter({'A': 2, 'A+': 2, 'B': 1, 'B+': 1})

 

>>> from collections import Counter
>>> Counter('GOOD LUCK')
Counter({'O': 2, 'G': 1, 'D': 1, ' ': 1, 'L': 1, 'U': 1, 'C': 1, 'K': 1}) #문자열에서 공백도 개수 셈.

>>> count = Counter('GOOD LUCK')
>>> count['D'], count['L']
(1, 1)

most_common() : 데이터의 개수가 많은 순으로 정렬된 배열을 리턴.

()안에 숫자를 넣으면 그 숫자의 크기 만큼 데이터 리턴. 1이면 데이터 1개, 2이면 데이터 2개...

>>> from collections import Counter
>>> Counter('GOOD LUCK').most_common()
[('O', 2), ('G', 1), ('D', 1), (' ', 1), ('L', 1), ('U', 1), ('C', 1), ('K', 1)]
>>> Counter('GOOD LUCK').most_common(1)
[('O', 2)]
>>> Counter('GOOD LUCK').most_common(2)
[('O', 2), ('G', 1)]