728x90
Counter()
- 문자열이나 리스트의 요소를 카운팅하여 많은 순으로 딕셔너리 형태로 리턴
- collections 모듈의 Counter 클래스
- 요소의 갯수를 세어준다
- key와 value 형태로 저장된다
- 덧셈 뺄셈 연산이 가능하다
most_common()
- ()안에 숫자를 전달하면 해당 개수만큼의 쌍을 반환
- 개수가 많은 순으로 정렬된 튜플 리스트를 리턴한다.
Counter() 사용 예제
from collections import Counter
arr = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4]
print(Counter(arr))
# Counter({1: 4, 3: 3, 2: 2, 4: 1})
print(Counter(arr).most_common(2))
# [(1, 4), (3, 3)]
cnt = Counter(arr).most_common()
print("key = ", cnt[0][0], "value = ", cnt[0][1])
# key = 1 value = 4
728x90
'Python' 카테고리의 다른 글
[Python] 파이썬 len() 사용법 (0) | 2022.07.29 |
---|---|
[Python] 파이썬 .join() 사용법 (0) | 2022.07.28 |
[Python] 파이썬 [], (), {} / 리스트, 튜플, 딕셔너리 차이 (0) | 2022.07.26 |
[Python] VSCode Git 연동하기 (0) | 2022.05.10 |
[Python] sort(), sorted() 차이 (0) | 2022.04.13 |