코딩하는 해맑은 거북이

[Python] Counter 클래스 정렬 방법 본문

Python/기본

[Python] Counter 클래스 정렬 방법

#CJE 2023. 1. 20.
해당 글은 Counter 클래스 정렬 방법 2가지를 다룬다.
1. key 정렬
2. value 정렬 (내림차순)

 

collections 모듈 Counter 클래스

from collections import Counter

먼저 Counter 클래스를 사용하기 위해선 위와 같은 모듈에서 불러와야 한다.

 

1. Key 정렬

sorted 함수로 딕셔너리의 key 순으로 정렬하는 방식과 같다. key의 이름순으로 정렬된다.

count = Counter('aabbbbcctttdefff')
print(sorted(count.items()))

    [('a', 2), ('b', 4), ('c', 2), ('d', 1), ('e', 1), ('f', 3), ('t', 3)]

 

2. Value 정렬

most_common() 함수를 사용해서 가장 흔하게 발생한 데이터 순으로(value 값이 큰 순서) 정렬한다.

count = Counter('aabbbbcctttdefff')
print(count.most_common())

    [('b', 4), ('t', 3), ('f', 3), ('a', 2), ('c', 2), ('d', 1), ('e', 1)]

 

Comments