[Python] collections.Counter() 이용한 빈도수 세기

yuseon Lim·2021년 9월 27일
0
post-thumbnail

😊 이전 블로그 글을 옮겨왔습니다.

collections.Counter()

Counter는 해시 가능한 객체를 세기 위한 dict의 서브 클래스. 요소가 딕셔너리 키로 저장되고 개수가 딕셔너리 값으로 저장되는 컬렉션.

LeetCode 819. Most Common Word와 같은 문제에서 키 존재 유무를 확인 할 필요 없이 즉시 Count 할 수 있다.

most_common([n])

n개의 가장 흔한 요소와 그 개수를 가장 흔한 것부터 가장 적은 것 순으로 나열한 리스트를 반환. n이 생략되거나 None이면 모든 요소를 반환.

리스트에서 가장 흔하게 등장하는 단어를 구하는 예제.

import collections

# apple3개, banana2개, cherry는 4개
list = ['apple', 'apple', 'apple', 'banana', 'banana',
        'cherry', 'cherry', 'cherry', 'cherry']

# 빈도수를 세려면?
counts = collections.Counter(list)
print(counts)

# 가장 흔하게 등장하는 단어의 첫번째 값을 most_common(1)로 추출
# most_common(1) => [('cherry',4)] _리스트
# most_common(1)[0] => ('cherry', 4) _ 튜플
# most_common(1)[0][0] => cherry _ 튜플에서 첫번째 추출
print('가장 흔한 단어는?: ', counts.most_common(1)[0][0])

결과

Counter({'cherry': 4, 'apple': 3, 'banana': 2})
가장 흔한 단어는?:  cherry

profile
🔥https://devyuseon.github.io/ 로 이사중 입니다!!!!!🔥

0개의 댓글