from collections import Counter
Counter 생성자는 여러 형태의 데이터를 인자로 받는데요.
먼저 중복된 데이터가 저장된 배열을 인자로 넘기면 각 원소가 몇 번씩 나오는지가 저장된 객체를 얻게 됩니다.
>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})
counter = Counter("hello world")
counter["o"], counter["l"]
(2, 3)
counter["l"] += 1
counter["h"] -= 1
counter
Counter({'h': 0, 'e': 1, 'l': 4, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
if "o" in counter:
print("o in counter")
del counter["o"]
if "o" not in counter:
print("o not in counter")
o in counter
o not in counter
Counter를 사용하는 것은 쉽지만 Counter를 만드는 것은 그만큼 간단하지는 않습니다.
def countLetters(word):
counter = {}
for letter in word:
if letter not in counter:
counter[letter] = 0
counter[letter] += 1
return counter
countLetters('hello world'))
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
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)]
K를 넘기면 그 숫자 만큼만 리턴하기 때문에, 가장 개수가 많은 K개의 데이터를 얻을 수도 있습니다.from collections import Counter
Counter('hello world').most_common(1)
[('l', 3)]
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)
Counter가 재밌는 부분은 바로 마치 숫자처럼 산술 연산자를 사용할 수 있다는 것인데요.
예를 들어, 아래와 같이 2개의 카운터 객체가 있을 때, 이 두 객체를 더할 수도 있고 뺄 수도 있다.
counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])
counter1 + counter2
Counter({'A': 3, 'B': 3})
뺄셈의 결과로 0이나 음수가 나온 경우에는 최종 카운터 객체에서 제외가 되니 이 부분 주의해서 사용하시길 바랍니다.
counter1 - counter2
Counter({'A': 1})