[Python]Counterクラス


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