Programming/Python

Python - Counter

wave35 2025. 3. 1. 11:36

생성 및 확인

from collections import Counter

# 리스트 요소 개수 세기
nums = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(nums)
print(counter)  # Counter({4: 4, 3: 3, 2: 2, 1: 1})

# 문자열 문자 개수 세기
text = "hello world"
counter = Counter(text)
print(counter)  # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

# 키인덱스
counter['l'] # 2

counter.values()
# dict_values([1, 1, 3, 2, 1, 1, 1, 1])

 

Counter 직접 구현

from collections import defaultdict

arr = [1, 2, 1, 3, 2, 1]
freq = defaultdict(int)

for num in arr:
    freq[num] += 1  # 값 증가

print(freq)  # defaultdict(<class 'int'>, {1: 3, 2: 2, 3: 1})

 

가장많이 카운팅 된 요소 확인

from collections import Counter

Counter('hello world').most_common()
# [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]

# 인자 사용하여 몇번째 사용문자인지 확인
Counter('hello world').most_common(1)
# [('l', 3)]

Counter('hello world').most_common(3)
# [('l', 3), ('o', 2), ('h', 1)]

 

산술연산자 사용

from collections import Counter
counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])

# 두 객체를 더하기
counter1 + counter2
# Counter({'A': 3, 'B': 3})