2022年4月29日金曜日

【標準ライブラリ】collections.Counterによる要素の出現回数カウント

 標準ライブラリcollectionsCounterを用いると要素の出現回数がカウントできる。戻り値はキーが要素、値が出現回数の辞書型のカウンターオブジェクトとなる。カウンターオブジェクトに対してカウンタツールmost_commonを適用すると出現回数が多い順に並べ替えることができる。

ライブラリcollectionsを使う際にはimportが必要。

import collections

又は以下のようにCounterをimportする。

from collections import Counter




1. collections.Counterによる要素の出現回数カウント

 Counterの引数にリストを与えるとキーが要素、値が出現回数の辞書型のカウンターオブジェクトが生成される。

from collections import Counter

a = [10, 50, 70, 30, 30, 50, 70, 20, 30, 10, 10, 30]
c = Counter(a)
print(c)

実行結果

Counter({10: 3, 50: 2, 70: 2, 30: 4, 20: 1})


from collections import Counter

a = ['10', '50', '70', '30', '30', '50', '70', 
     '20', '30', '10', '10', '30']
c = Counter(a)
print(c)

実行結果

Counter({'10': 3, '50': 2, '70': 2, '30': 4, '20': 1})


2. most_commonによる出現回数順の並べ替え

 カウンターオブジェクトに対して、most_common()メソッドを適用することで、出現回数が多い順にキーと値が並べ替えられる。

from collections import Counter

a = ['10', '50', '70', '30', '30', '50', '70', 
     '20', '30', '10', '10', '30']
c = Counter(a)
print(c.most_common())

実行結果

[('30', 4), ('10', 3), ('50', 2), ('70', 2), ('20', 1)]


 most_common()メソッドの引数に個数を指定すると、出現回数が多い順に指定した個数だけ求められる。

from collections import Counter

a = ['10', '50', '70', '30', '30', '50', '70', 
     '20', '30', '10', '10', '30']
c = Counter(a)
print(c.most_common(3))

実行結果

[('30', 4), ('10', 3), ('50', 2)]


2. リファレンス

Python 標準ライブラリ > collections --- コンテナデータ型 > class collections.Counter([iterable-or-mapping])
Python 標準ライブラリ > collections --- コンテナデータ型 > most_common([n])

使用バージョン:Python 3.9.12

0 件のコメント:

コメントを投稿