Coding Practice/Python
List - 요소 별 Count
LazyHand
2024. 7. 16. 19:02
List는 가장 기본이 되는 자료구조이다.
종종, List 내 요소들에 대해 Counting을 알고 싶어질 때가 있는데,
그럴 땐 Collections
라이브러리의 Counter 함수를 활용하면 된다.
List의 요소가 문자열이 아닌 숫자여도 동일하게 사용하면 된다.
from collections import Counter
# 예시 리스트
elements = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'kiwi', 'kiwi']
# Counter를 사용하여 요소별 개수 세기
element_counts = Counter(elements)
# 결과 출력
print(element_counts)
#Counter({'apple': 3, 'banana': 2, 'orange': 1, 'kiwi': 2})
간단하지만, 가끔 잊게되어 정리하게된 Counter 함수이다.