Algorithm/Python

Python - Counter

yxemsy 2022. 2. 4. 11:36
  • collections 라이브러리의 Counter는 리스트와 같은 객체에서 내부에 원소가 몇 번 등장하는지 알려준다.
from collections import Counter

counter = Counter(['dog', 'cat', 'dog', 'dog', 'cat'])

print(counter['dog'])
print(counter['cat'])
print(dict(counter))

실행결과

3
2
{'dog': 3, 'cat': 2}