최대 1 분 소요


collections - Counter

파이썬의 기본 자료구조인 사전(dictionary)를 확장하고 있기 때문에, 사전에서 제공하는 API를 그대로 다 시용할 수가 있다.

In [1]:
from collections import Counter
In [2]:
word = 'hello world'
In [3]:
Counter(word)
Out [3]:
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
In [4]:
# Counter 구현
cnt = {}
for w in word:
    if w not in cnt:
        cnt[w] = 0
    cnt[w] += 1
cnt
Out [4]:
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

댓글남기기