collections.Counter 클래스를 사용하여 데이터의 개수를 효율적으로 셀 수 있다.

https://docs.python.org/ko/3/library/collections.html#collections.Counter

 

collections — 컨테이너 데이터형 — Python 3.10.5 문서

collections — 컨테이너 데이터형 소스 코드: Lib/collections/__init__.py 이 모듈은 파이썬의 범용 내장 컨테이너 dict, list, set 및 tuple에 대한 대안을 제공하는 특수 컨테이너 데이터형을 구현합니다. named

docs.python.org

 

collections.Counter

from collections import Counter

Counter('collections Counter')
# Counter({'o': 3, 'c': 2, 'l': 2, 'e': 2, 't': 2, 'n': 2, 'i': 1, 's': 1, ' ': 1, 'C': 1, 'u': 1, 'r': 1})Copy Icon

 

Dictionary 처럼 사용하기

기본 자료구조인 사전(Dictionary) 기능을 그대로 사용이 가능합니다.

from collections import Counter

counter = Counter("collections Counter")
print(counter)
# Counter({'o': 3, 'c': 2, 'l': 2, 'e': 2, 't': 2, 'n': 2, 'i': 1, 's': 1, ' ': 1, 'C': 1, 'u': 1, 'r': 1})

# list도 가능
counter = Counter([6, 3, 2, 10, 10, 10, -10, -10, 7, 3])
print(counter)
# Counter({10: 3, 3: 2, -10: 2, 6: 1, 2: 1, 7: 1})Copy Icon

 

from collections import Counter

counter = Counter("collections Counter")
print(counter)
# Counter({'o': 3, 'c': 2, 'l': 2, 'e': 2, 't': 2, 'n': 2, 'i': 1, 's': 1, ' ': 1, 'C': 1, 'u': 1, 'r': 1})

counter["C"] += 2
counter["l"] -= 1
del counter["o"]
print(counter)
# Counter({'C': 3, 'c': 2, 'e': 2, 't': 2, 'n': 2, 'l': 1, 'i': 1, 's': 1, ' ': 1, 'u': 1, 'r': 1})
print("r" in counter)
# True

## list도 가능
counter = Counter([6, 3, 2, 10, 10, 10, -10, -10, 7, 3])
print(counter)
# Counter({10: 3, 3: 2, -10: 2, 6: 1, 2: 1, 7: 1})

counter[10] -= 2
counter[7] += 2
del counter[-10]
print(counter)
# Counter({7: 3, 3: 2, 6: 1, 2: 1, 10: 1})
print(2 not in counter)
# FalseCopy Icon

 

Method

  • elements() : 개수만큼 반복되는 요소 반환
  • most_common(n) : 빈도수가 가장 높은 요소를 순서대로 n개 반환
  • subtract() : 해당 요소를 제거, 개수가 0보다 작을시 음수
  • update() : Counter의 값 갱신
import collections scores = ['A', 'B', 'B', 'C', 'C', 'D', 'A']
counter = collections.Counter(scores) print(counter)

# update()
score2 = ['C','D']
counter.update(score2)
print(counter)
# Counter({'A': 2, 'B': 2, 'C': 2, 'D': 1})
# Counter({'C': 3, 'A': 2, 'B': 2, 'D': 2})

# elements()
list(counter.elements())
# ['A', 'A', 'B', 'B', 'C', 'C', 'C', 'D', 'D']

# most_common()
counter.most_common(2)
# [('C', 3), ('A', 2)]

# subtract()
counter.subtract(score2)
print(counter)
# Counter({'A': 2, 'B': 2, 'C': 2, 'D': 1})Copy Icon

 

ex) 가장 많이 등장하는 알파벳과 그 알파벳의 개수

from collections import Counter

def find_max(word):
    counter = Counter(word)
    max_count = -1
    for letter in counter:
        if counter[letter] > max_count:
            max_count = counter[letter]
            max_letter = letter
    return max_letter, max_count

find_max('hello world') # ('l', 3)Copy Icon

'Develop > Python' 카테고리의 다른 글

[Python] 큐 (Queue)  (0) 2022.08.02
[Python] 시간 복잡도  (0) 2022.08.02
[Python] 그리디 (Greedy)  (0) 2022.06.06
[Python] cmp_to_key() - 원하는 기준으로 sort() (정렬) 하기  (0) 2022.06.01
[Python] re (정규 표현식)  (0) 2022.05.14
욱근욱