언어/Python
[Python] collections 모듈의 Counter 함수
SeongOnion
2021. 4. 4. 23:04
728x90
알고리즘 문제를 풀다가 알게된 함수로, 꽤 유용하다고 생각하였으나 역시나 얼마 동안 안쓰니 다 까먹어버려 다시 한 번 정리하고자 글을 남긴다.
Counter 함수는 deque를 지원하는 collectinos 모듈을 통해서 이용 가능하다.
from collectinos import Counter
따라서 다음과 같이 위에서 import 해온 후 사용 가능하다.
Counter 함수는 특정 문자 혹은 원소의 갯수를 세어 딕셔너리 형태로 리턴 해주는 함수이다.
from collections import Counter
my_text = "Hello,World!"
my_counter = Counter(my_text)
print(my_counter)
보다시피 각 문자에 대한 갯수를 올바르게 출력해온 것을 알 수 있다.
물론, Counter는 리스트에도 이용할 수 있다.
from collections import Counter
my_list = ['cat', 'cat', 'dog', 'dog', 'lion']
my_counter = Counter(my_list)
print(my_counter)
아래의 문제는 collections.Counter를 활용해 풀 수 있는 문제이다.
programmers.co.kr/learn/courses/30/lessons/42576
코딩테스트 연습 - 완주하지 못한 선수
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수
programmers.co.kr