Counter 클래스는 collections 모듈을 이용해서 별도 패키지 설치 없이 사용할 수 있는 함수이다.
여러 형태의 데이터를 인자로 받을 수 있으며 각 원소가 몇 번씩 나오는지 알려주는 함수이다.
Counter 함수 사용 방법
1.
>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})
Counter 클래스에 인자로 리스트를 넣을시 리스트 내부에서 몇번 나왔는지 출력된다.
2.
>>> Counter("hello world")
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
Counter 클래스에 인자로 문자열을 넣을시 문자열에서 각각의 문자가 몇 번 나왔는지를 출력한다.
3.
counter = Counter("hello world")
counter["o"], counter["l"]
>>(2, 3)
Counter 클래스는 사전 자료구조를 확장한 형태이기에 사전에서 사용할 수 있는 API를 그대로 다 사용할 수 있다.
counter["l"] += 1
counter["h"] -= 1
counter
>> Counter({'h': 0, 'e': 1, 'l': 4, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
특정 키에 해당하는 값 또한 추가하거나 제거하거나 할 수 있다.
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
if문을 이용해서 특정 키가 카운터 내에 존재하는지도 알 수 있다.
from collections import Counter
Counter('hello world').most_common()
>> [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]
most_common() 메서드를 통해서 데이터의 개수가 많은 순으로 정렬할 수 있다.
Counter 함수 미사용시 구현
def countLetters(word):
counter = {}
for letter in word:
if letter not in counter:
counter[letter] = 0
counter[letter] += 1
return counter
countLetters('hello world'))
>> {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 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')
>> ('l', 3)
Counter 함수의 산술 연산
Counter 함수는 산술 연산을 통해서 결과값을 더하거나 빼거나 등을 수행할 수 있다.
counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])
counter1 + counter2
>> Counter({'A': 3, 'B': 3})
뺄셈의 결과로 0 이하의 정수가 나온 경우에는 출력값에서 제외된다.
'파이썬 기초 지식(for algorithm)' 카테고리의 다른 글
Python(파이썬) -split() 개념 (0) | 2023.07.18 |
---|---|
Python(파이썬) -String strip(), rstrip(), lstrip() 개념 (0) | 2022.03.20 |