collections 모듈의 Counter 클래스
from collections import Counter
pool = ['hello', 'world', 'hello', 'hello']
print(Counter(pool))
# 결과 : Counter({'hello': 3, 'world': 1})
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})
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
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']
데이터의 개수가 많은 순으로 정렬된 배열을 반환하는 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)]