🍒공부/Python
[Python] collections.Counter
rindev
2020. 12. 29. 23:39
docs.python.org/ko/3/library/collections.html?highlight=collection#collections.Counter
collections — Container datatypes — Python 3.9.1 문서
collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f
docs.python.org
이걸 알게된 건 백준 정렬 > 통계학 문제를 풀다가....ㅠㅠ
최빈값을 구하려고 count를 했더니 시간초과가 나서 다른사람들은 어떻게 풀었는지 궁금해서 검색하다가 알게됐다!
까먹기전에 정리해둬야지..ㅠㅠ
Counter를 쓰기 위해서는 from collections import Counter 라고 임포트를 해줘야 한다
그리고 most_common을 해주면 많이 등장한 값부터 내림차순으로 정렬해준다.
등장 횟수가 같을 시 앞의 값으로 정렬한다.
freqs = Counter(nums).most_common() #nums = [3,3,2,1,4,4,5]
print(freqs) #[(3, 2), (4, 2), (1, 1), (2, 1), (5, 1)]