Python collections.Counter:効率的なカウント、更新、演算操作
Python collections.Counter:効率的なカウント、更新、演算操作
PythonのCounterは、イテラブル内の各要素の出現回数を数える特殊なコンテナです。dictを継承し、要素をキー、カウントを値として格納するため、ハッシュテーブル形式のカウントに最適です。
Python Counterを使う理由
- データを無順序なハッシュテーブル風構造で格納;要素をキー、カウントを値とする
- 文字列、リスト、タプル、辞書など任意のイテラブルのアイテムカウントが簡単
- 組み込みの演算操作(加算、減算、積集合、和集合)で強力なセット風操作が可能
- 他の
Counterインスタンスからのカウント集計をシームレスに実行
Counterの始め方
collectionsからクラスをインポート:
from collections import Counter
任意のイテラブルをCounterに渡してカウントマッピングを取得:
例 – リストのカウント
list1 = ['x','y','z','x','x','x','y','z'] print(Counter(list1))
出力:
Counter({'x': 4, 'y': 2, 'z': 2})
例 – 文字列のカウント
my_str = "Welcome to Guru99 Tutorials!" print(Counter(my_str))
出力:
Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})
例 – 辞書のカウント
dict1 = {'x': 4, 'y': 2, 'z': 2}
print(Counter(dict1))
出力:
Counter({'x': 4, 'y': 2, 'z': 2})
例 – タプルのカウント
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))
出力:
Counter({'x': 4, 'y': 2, 'z': 2})
Counterの初期化、更新、アクセス
初期化
print(Counter("Welcome to Guru99 Tutorials!")) # 文字列
print(Counter(['x','y','z','x','x','x','y','z'])) # リスト
print(Counter({'x': 4, 'y': 2, 'z': 2})) # 辞書
print(Counter(('x','y','z','x','x','x','y','z'))) # タプル
# 空のカウンター
_count = Counter()
更新
_count.update('Welcome to Guru99 Tutorials!')
print(_count)
出力:
Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})
カウントへのアクセス
print('%s : %d' % ('u', _count['u']))
for char in 'Guru':
print('%s : %d' % (char, _count[char]))
出力:
u : 3 G : 1 u : 3 r : 2 u : 3
要素の削除
del _count['x'] print(_count)
出力:
Counter({'y': 2, 'z': 2})
演算操作
Counterはセット風の演算をサポート。正のカウントは保持;結果では負の値は破棄されます。
counter1 = Counter({'x': 4, 'y': 2, 'z': -2})
counter2 = Counter({'x1': -12, 'y': 5, 'z': 4})
# 加算
print(counter1 + counter2)
# 減算
print(counter1 - counter2)
# 積集合
print(counter1 & counter2)
# 和集合
print(counter1 | counter2)
出力:
Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})
主要メソッド
- elements() – 正のカウントを持つ要素のイテレータを返す
- most_common([n]) – 上位n個の要素を(要素, カウント)タプルのリストで返す
- subtract(other) – 他のCounterからカウントを減算
- update(other) – 他のCounterからカウントを加算
elements()の使用
counter = Counter({'x': 5, 'y': 2, 'z': -2, 'x1': 0})
for e in counter.elements():
print(e)
出力:
x x x x x y y
most_common()の使用
counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter.most_common(2))
print(counter.most_common())
出力:
[('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]
subtract()の使用
c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})
c1.subtract(c2)
print(c1)
出力:
Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})
update()の使用
c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})
c1.update(c2)
print(c1)
出力:
Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})
カウントの再代入
counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
counter['y'] = 20
print(counter)
出力:
Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})
要素カウントの取得と設定
counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter['y'])
counter['y'] = 20
counter['y1'] = 10
print(counter)
出力:
12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})
まとめ
- Counterは任意のイテラブルの要素を数える辞書サブクラス
- 効率的なカウント、演算操作、ユーティリティメソッド群をサポート
- 頻度分析、ヒストグラム生成、データ集計などが一般的ユースケース
- 詳細ドキュメントはPython Counter公式ドキュメントを参照
Python
- Python strip()メソッド完全ガイド:実践例付き
- Python str.count()マスター:文字と部分文字列のカウント実例集
- Python format()文字列を明確な例でマスター
- Python len()関数:オブジェクトの長さを測る実践ガイド
- Python String.find()メソッド完全ガイド:構文、例、代替手法
- Pythonラムダ関数をマスターする:実例とベストプラクティス
- Python round()関数を実例で徹底解説
- Python map()関数をマスター:構文、例、ベストプラクティス
- Python timeit():実行時間測定の実例付きガイド
- Python list.count() 完全ガイド:実践例付きで徹底解説
- Python list.index():要素の位置を検索する実践ガイド