collections.Counter로 카운팅

Dong-Hyeon Park·2021년 12월 28일
0

Python Skills

목록 보기
1/7
post-thumbnail

문자열 "hello word"에 출현하는 알파벳 개수를 세고 싶을 때

0. 뻔한 방식 -> dictionary 사용

1. collections.Counter를 이용한 카운팅

from collections import Counter

Counter('hello world') # dictionary와 비슷한 형식의 Counter 객체 리턴
Counter('hello world').most_common() # 카운트가 높은 순으로 key, value 튜플이 담긴 list 객체 리턴
Counter('hello world').most_common(1) # 매개 변수로 전달한 숫자 만큼의 데이터를 담은 리스트 리턴

문자열을 Counter에 전달하면 문자 하나하나를 세고,
여러 문자열이 담긴 list를 전달하면 문자열을 한개씩 센다.

profile
Android Engineer from KU CSE

0개의 댓글