[Python] Counter 클래스

Jiin Kim·2021년 8월 20일
0

collections 모듈의 Counter 클래스

1. 리스트

from collections import Counter

pool = ['hello', 'world', 'hello', 'hello']
print(Counter(pool))

# 결과 : Counter({'hello': 3, 'world': 1})

2. 문자열

from collections import Counter

pool = 'python pytorch tensorflow'
print(Counter(pool))

# 결과 : Counter({'o': 4, 't': 3, 'p': 2, 'y': 2, 'h': 2, 'n': 2, ' ': 2, 'r': 2, 'c': 1, 'e': 1, 's': 1, 'f': 1, 'l': 1, 'w': 1})

3. Counter 클래스의 반환값

Counter 클래스의 반환값은 딕셔너리 형태이다.

from collections import Counter

pool = 'hello world'
count_list = Counter(pool)

for key, value in count_list.items():
    print(key, ' : ', value)
    
# 결과
h  :  1
e  :  1
l  :  3
o  :  2
   :  1
w  :  1
r  :  1
d  :  1

4. Counter 클래스에 파라미터 넣기

from collections import Counter

count_list = Counter(a=1, b=4, c=2)
print(count_list)
print(sorted(count_list.elements()))

# 결과
Counter({'b': 4, 'c': 2, 'a': 1})
['a', 'b', 'b', 'b', 'b', 'c', 'c']

5. 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)]
from collections import Counter

Counter('hello world').most_common(1)
# 결과 : [('l', 3)]

Counter('hello world').most_common(1)
# 결과 : [('l', 3), ('o', 2)]
profile
컴퓨터 비전을 공부하는 대학원생

0개의 댓글

관련 채용 정보