파이썬 Counter

allnight5·2022년 11월 16일
0

python 함수

목록 보기
3/12

Counter 기본 사용법

from collections import Counter

Counter 생성자는 여러 형태의 데이터를 인자로 받는데요. 먼저 중복된 데이터가 저장된 배열을 인자로 넘기면 각 원소가 몇 번씩 나오는지가 저장된 객체를 얻게 됩니다.

Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})

Counter를 사전처럼 사용하기

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

예를 들어, 대괄호를 이용하여 키로 값을 읽을 수 있고요.

counter = Counter("hello world")
counter["o"], counter["l"]
(2, 3)
특정 키에 해당하는 값을 갱신할 수도 있다.

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")

출력결과

o in counter
o not in counter

사전(dictionary)으로 Counter 흉내하기
Counter를 사용하는 것은 쉽지만 Counter를 만드는 것은 그만큼 간단하지는 않습니다.

일반 사전을 이용하여 어떤 단어가 주어졌을 때 단어에 포함된 각 알파벳의 글자 수를 세어주는 함수를 작성해보겠습니다.

def countLetters(word):
counter = {}
for letter in word:
if letter not in counter:
counter[letter] = 0
counter[letter] += 1
return counter

가장 흔한 데이터 찾기
아마도 실전에서 Counter가 자주 쓰이는 경우는 가장 많이 나온 데이터나 가장 적게 나온 데이터를 찾을 때일 것일 텐데요.

Counter 클래스는 이와 같은 작업을 좀 더 쉽게 할 수 있도록, 데이터의 개수가 많은 순으로 정렬된 배열을 리턴하는 most_common()이라는 메서드를 제공하고 있습니다.

Counter('hello world').most_common()

#1번이 가장 큰 빈도수를 가지고 있다.
Counter('hello world').most_common(1)

Counter의 most_common() 함수가 없었다면

가장 많은 나온 데이터를 구하려면 다음과 같은 함수를 직접 작성했어야겠죠?

from collections import Counter

def find_max(word):
    counter = Counter(word)
    max_count = -1
    for letter in counter:
        if counter[letter] > max_count:
            max_count = counter[letter]
            max_letter = letter
    return max_letter, max_count

find_max('hello world')

출처 : https://www.daleseo.com/python-collections-counter/

profile
공부기록하기

0개의 댓글