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
- numpy.arange(), 균일 간격 배열
- numpy.concatenate(), 배열 합치기
- numpy hstack, vstack 함수 (배열 연결)
- numpy.average(), 배열 가중 평균
- Numpy 배열을 List로 변환
- 파이썬 List를 Numpy 배열로 변환
- numpy flatten() 함수, 1차원 배열로 변환(평탄화)
- numpy의 min(), max() 함수 (최소, 최대 값)
- numpy.mean(), 배열 평균 계산
- numpy.log(), 로그 함수 사용 방법
- numpy.shape(), 배열 크기/형태/차원 확인
- numpy.sqrt(), 배열의 제곱근 계산
- numpy.zeros(), 0으로 채워진 배열 생성
- Python Numpy 버전 확인 방법
- numpy.argsort(), 배열 정렬
- numpy.clip(), 배열의 최대/최소 값 지정
- numpy.linspace(), 동일 간격 숫자 배열
- Numpy - random 모듈, 난수 배열 생성
- Numpy의 ndarray 사용 방법 알아보기
- numpy.transpose(), 전치 행렬 변환
- Numpy - where() 사용 방법
- Python - numpy.append(), 배열 추가
- Python numpy.random.choice(), 랜덤 샘플링
- Python numpy.reshape(), 배열 차원 변경
- Python numpy.sum(), 배열의 합
- Python numpy.unique(), 배열 중복 제거
- Python - json.dumps()로 JSON 출력하기
- Python - find() 문자 위치 찾기
- Python lower() 문자열 소문자로 변환
- Python upper() 문자열 대문자로 변환
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제