collections module의 Counter() class

SSW·2022년 8월 9일
0

Python

목록 보기
3/5

* collections.Counter()

Python에서 항목(keys)들의 갯수를 셀 때 이 Counter()를 사용하면 각 항목들의 갯수들이 한번에 알아서 출력된다. 또한 항목의 갯수가 많은 순서대로 내림차순으로 정렬되어 출력된다. collections module의 Counter class는 python의 기본 자료구조인 dictionary를 확장하고 있기 때문에, dictionary에서 제공하는 API를 그대로 다 사용할 수 있다.

Example1

from collections import Counter

fluit1 = ['apple', 'orange', 'strawberry', 'orange', 'apple','melon', 'orange']
result1 = Counter(fluit1)
print(result1)

fluit1 list에 들어있는 각 항목들의 갯수를 출력한다.

<output>
Counter({'orange': 3, 'apple': 2, 'strawberry': 1, 'melon': 1})

Example2

from collections import Counter

result3 = Counter('Hello, have a good day!')
print(result3)

print(result3.most_common(2))
print(result3.most_common(4))

Counter()에 문자열을 대입하여 문자열 내에 각 알파벳과 공백의 갯수를 출력하고, .most_common() method를 사용하여 인자만큼 상위 원소들을 출력한다.

<output>
Counter({' ': 4, 'o': 3, 'a': 3, 'e': 2, 'l': 2, 'd': 2, 'H': 1, ',': 1, 'h': 1, 'v': 1, 'g': 1, 'y': 1, '!': 1})
[(' ', 4), ('o', 3)]
[(' ', 4), ('o', 3), ('a', 3), ('e', 2)]

Example3

from collections import Counter

fluit1 = ['apple', 'orange', 'strawberry', 'orange', 'apple','melon', 'orange']
fluit2 = ['orange', 'apple', 'apple', 'orange', 'melon']

result1 = Counter(fluit1)
result2 = Counter(fluit2)
print(result1 + result2)

두 Counter()를 더하여 두 list 내에 있는 각 항목들의 총 갯수들을 출력한다.

<output>
Counter({'orange': 5, 'apple': 4, 'melon': 2, 'strawberry': 1})

Example4

from collections import Counter

fluit1 = ['apple', 'orange', 'strawberry', 'orange', 'apple','melon', 'orange']

print(result1.most_common(1))
print(result1.most_common(3))
print(result1.most_common(5))

위에서 언급한 것처럼 .most_common() method를 사용하여 들어가는 인자만큼 상위 원소들을 return한다. 이 때, 항목의 갯수 이상의 수가 인자로 사용될 경우에는 .most_common() method를 사용하지 않은 것과 같은 결과가 출력된다.

<output>
[('orange', 3)]
[('orange', 3), ('apple', 2), ('strawberry', 1)]
[('orange', 3), ('apple', 2), ('strawberry', 1), ('melon', 1)]

Example5

from collections import Counter

fluit1 = ['apple', 'orange', 'strawberry', 'orange', 'apple','melon', 'orange']
fluit2 = ['orange', 'apple', 'apple', 'orange', 'melon']

result1 = Counter(fluit1)
result2 = Counter(fluit2)
print(result1)
print(result2)

result1.subtract(result2)
print(result1)

덧셈을 할 수 있는 것처럼 .substract()를 이용하여 뺄셈도 할 수 있다.

<output>
Counter({'orange': 3, 'apple': 2, 'strawberry': 1, 'melon': 1})
Counter({'orange': 2, 'apple': 2, 'melon': 1})
Counter({'orange': 1, 'strawberry': 1, 'apple': 0, 'melon': 0})

profile
ssw

0개의 댓글