Today I Learned 37 - python / collections 모듈의 Counter 객체

angie·2022년 8월 19일
0

Python

목록 보기
11/11
post-thumbnail
임포트
from collections import Counter
기본적인 사용법
  • 중복된 데이터가 저장된 배열을 인자로 넘기면 각 원소가 몇 번씩 나오는지가 저장된 객체를 얻게 됩니다.
>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})
  • 문자열을 인자로 넘기면 각 문자가 문자열에서 몇 번씩 나타나는지를 알려주는 객체가 반환
>>> Counter("hello world")
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

딕셔너리처럼 사용

  • 딕셔너리에서 제공하는 API 모두 사용 가능
# 키로 값에 접근
counter = Counter("hello world")
counter["o"], counter["l"]

# 키로 값에 접근하여 값을 갱신
counter["l"] += 1
counter["h"] -= 1

# if 문에서 in 키워드를 이용하여 특정 키가 카운터에 존재하는지를 확인
if "o" in counter:
    print("o in counter")

del counter["o"]

if "o" not in counter:
    print("o not in counter")
  • 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)]

산술 연산자 활용

  • 숫자처럼 산술 연산자를 사용할 수 있다!
counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])

# 더하기
counter1 + counter2
>>> Counter({'A': 3, 'B': 3})

# 빼기
counter1 - counter2
>>> Counter({'A': 1})
profile
better than more

0개의 댓글