collections - Counter
collections - Counter
파이썬의 기본 자료구조인 사전(dictionary)를 확장하고 있기 때문에, 사전에서 제공하는 API를 그대로 다 시용할 수가 있다.
from collections import Counter
word = 'hello world'
Counter(word)
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# Counter 구현
cnt = {}
for w in word:
if w not in cnt:
cnt[w] = 0
cnt[w] += 1
cnt
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
댓글남기기