Counter

발자·2023년 6월 6일
0

python

목록 보기
18/19

Counter

collections 모듈의 Counter 클래스를 임포트해서 사용

from collections import Counter
sample = "aabbbc"
counter = Counter(sample)
print(counter)
# 출력 Counter({'b': 3, 'a': 2, 'c': 1})

출력된 형식을 보면 dictionary 형태이므로 다음과 같이 사용할 수 있다.

print(counter['a'])
# 출력 2
counter['b'] -= 2
counter['c'] += 2
print(counter)
# 출력 Counter({'c': 3, 'a': 2, 'b': 1})
print(True if 'a' in counter else False)
# 출력 True
del counter['c']
print(counter)
# 출력 Counter({'a': 2, 'b': 1})
new_counter = Counter(["b", "c", "c"])
print(new_counter)
# 출력 Counter({'c': 2, 'b': 1})
counter2 = counter + new_counter
print(counter2)
# 출력 Counter({'a': 2, 'b': 2, 'c': 2})
counter3 = counter - new_counter
print(counter3)
# 출력 Counter({'a': 2})
print(counter2.most_common())
# 출력 [('a', 2), ('b', 2), ('c', 2)]

0개의 댓글