Counter는 list, dict 등의 Collections에서 동일 요소가 몇개나 있는지 개수를 셀 때 사용합니다.
또한, 개수가 많은 순서대로 정렬하기 때문에 가장 많은 요소가 무엇인지 알 수 있습니다.
예를 들어, 아래와 같은 리스트에 대해서 Counter를 적용하면, result와 같이 개수를 세서 순서대로 정렬해 줍니다.
list : ['a', 'b', 'c', 'a', 'b', 'b', 'd']
result : {'b': 3, 'a': 2, 'c': 1, 'd': 1}
1. 리스트의 요소 개수 세기
아래와 같이 Counter를 사용하여 리스트의 요소 개수를 셀 수 있습니다.
Counter(list)
: 리스트의 요소 개수를 세고 Counter로 리턴counter[item]
: 요소를 key로 입력하면 개수를 리턴
from collections import Counter
my_list = ['a', 'b', 'c', 'a', 'b', 'b', 'd']
counter = Counter(my_list)
print(counter)
count_b = counter['b']
print(f"b: {count_b}")
Output:
Counter({'b': 3, 'a': 2, 'c': 1, 'd': 1})
b: 3
2. 가장 많은 요소 찾기
Counter.most_common(n)
는 가장 많은 개수의 요소들을 n개만 리스트로 리턴합니다. 리스트는 요소 개수로 내림차순 정렬되며, (element, count)
처럼 요소와 개수를 Tuple로 묶어서 리스트에 저장되어있습니다.
아래와 같이 Tuple에 접근하여 요소 및 개수를 접근할 수 있습니다.
most_common[0][0]
: 가장 많은 요소 값most_common[0][1]
: 가장 많은 요소의 개수
from collections import Counter
elements = ['a', 'b', 'c', 'a', 'b', 'b', 'd']
counter = Counter(elements)
most_common = counter.most_common(2)
print(most_common)
print(f"the most common key: {most_common[0][0]}")
print(f"the number of the most common: {most_common[0][1]}")
Output:
[('b', 3), ('a', 2)]
the most common key: b
the number of the most common: 3
3. 문자열의 문자 개수 세기
아래와 같이 Counter
를 이용하여 문자열의 문자 개수를 셀 수 있습니다.
from collections import Counter
str = "Hello, World, Python"
counter = Counter(str)
print(counter)
count_o = counter['o']
print(f"o: {count_o}")
Output:
Counter({'l': 3, 'o': 3, ',': 2, ' ': 2, 'H': 1, 'e': 1, 'W': 1, 'r': 1, 'd': 1, 'P': 1, 'y': 1, 't': 1, 'h': 1, 'n': 1})
o: 3
4. 두개의 Counter 더하기
두개의 Collection에 대한 Counter 객체를 더할 수 있습니다.
즉, 두 Collection을 더하지 않아도, 각각의 Counter를 더해서 전체 요소 개수를 계산할 수 있습니다.
아래와 같이 dict에 대한 Counter를 생성하고, 두개의 Counter를 더하면 각각의 개수가 합쳐집니다.
from collections import Counter
my_dict1 = {'apple': 3, 'banana': 2, 'orange': 5}
my_dict2 = {'apple': 1, 'kiwi': 3, 'orange': 2}
counter1 = Counter(my_dict1)
counter2 = Counter(my_dict2)
counter_sum = counter1 + counter2
print(f"counter1: {counter1}")
print(f"counter2: {counter2}")
print(f"sum: {counter_sum}")
Output:
counter1: Counter({'orange': 5, 'apple': 3, 'banana': 2})
counter2: Counter({'kiwi': 3, 'orange': 2, 'apple': 1})
sum: Counter({'orange': 7, 'apple': 4, 'kiwi': 3, 'banana': 2})
Loading script...
Related Posts
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제
- Python - count(), len() 함수
- Python - join() 함수, 문자열 합치기
- Python - 줄바꿈 입력 방법
- Python - 딕셔너리를 JSON으로 변환
- Python - JSON을 딕셔너리로 변환
- Python - 딕셔너리 Index로 접근/순회 방법
- Python - 딕셔너 리 CSV 파일 쓰기/읽기
- Python - 딕셔너리 update() 함수
- Python - JSON 예쁘게(pretty), 정렬하여 출력
- Python - CSV 파일을 JSON 파일로 변환
- Python - CSV 파일을 리스트로 변환
- Python - List를 Set로 변환
- Python - Set을 List로 변환
- Python - 텍스트 파일 이어서 쓰기
- Python - 파일 끝 찾기
- Python - 파일 수정 시간, 생성 시간 확인