임포트
from collections import Counter
기본적인 사용법
- 중복된 데이터가 저장된 배열을 인자로 넘기면 각 원소가 몇 번씩 나오는지가 저장된 객체를 얻게 됩니다.
>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})
- 문자열을 인자로 넘기면 각 문자가 문자열에서 몇 번씩 나타나는지를 알려주는 객체가 반환
>>> Counter("hello world")
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
딕셔너리처럼 사용
counter = Counter("hello world")
counter["o"], counter["l"]
counter["l"] += 1
counter["h"] -= 1
if "o" in counter:
print("o in counter")
del counter["o"]
if "o" not in counter:
print("o not in counter")
most_common()
: 데이터의 개수가 많은 순으로 정렬된 배열을 리턴
from collections import Counter
Counter('hello world').most_common()
>>> [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]
산술 연산자 활용
counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])
counter1 + counter2
>>> Counter({'A': 3, 'B': 3})
counter1 - counter2
>>> Counter({'A': 1})