Python: カウンタ。Counter()関数で要素数を計算する

TwitterFacebookHatena
  • 公開:2021-11-29
  • 更新:2023-10-26
  • 文章量:1798
  • Python

TL;DR

Python 標準ライブラリである collections の Counter()関数は要素数の計算を行う。出現の回数を集計する場合などに便利である。

Counter()クラス のポイント

  • ハッシュ(辞書)可能なオブジェクトを数え要素数を返す
  • イテラブル、マッピング、キーワード引数のオブジェクトを数える
  • 和集合・減算・積集合などが可能
  • subtract()で減算を行う
  • most_common()で要素を降順で返す
c = Counter()
# 空のカウンターを作成する

c = Counter('gallahad')
# イテラブルなカウンター作成

c = Counter({'red': 4, 'blue': 2})
# マッピング

c = Counter(cats=4, dogs=8)
# キーワード引数セット

ハッシュ可能なオブジェクトを数え上げる辞書(dict)のサブクラス。要素を辞書のキーとして保存し、そのカウントを辞書の値として保存するコレクション。 collections --- コンテナデータ型 — Python 3.10.0b2 ドキュメント

Counter()

要素数を数える。存在しない要素には 0 を返す。

from collections import Counter
c = Counter(['a', 'a', 'b', 'c'])
c['a']
# 2

イテラブルな要素を数える。イテラブルなオブジェクトとは、リスト、タプル、辞書、文字列など複数の要素を持ったオブジェクトを指す。

次のコードでは、タプルや文字もイテラブルなのでカウントされている。

c = Counter('abbbd')
c
# Counter({'a': 1, 'b': 3, 'd': 1})

c = Counter(('a', 'a', 'a', 'b', 'c', 'c'))
c
# Counter({'a': 3, 'b': 1, 'c': 2})

結合

リストの結合。

one = Counter(['a', 'a', 'a', 'b', 'c', '
```markdown
c', 'c'])
two = Counter(['a', 'b', 'b', 'b', 'c'])
three = one + two
print(three)
# Counter({'a': 4, 'b': 4, 'c': 3})

差分

one = Counter(['a', 'a', 'a', 'b', 'c', 'c', 'c'])
two = Counter(['a', 'b', 'b', 'b', 'c'])
three = one - two
print(three)
# Counter({'a': 2, 'c': 2})

交差点

one = Counter(['a', 'a', 'a', 'b', 'c', 'c', 'c'])
two = Counter(['a', 'b', 'b', 'b', 'c'])
three = one & two
print(three)
# Counter({'a': 1, 'b': 1, 'c': 1})

積集合

one = Counter(['a', 'a', 'a', 'b', 'c', 'c', 'c'])
two = Counter(['a', 'b', 'b', 'b', 'c'])
three = one | two
print(three)
# Counter({'a': 3, 'b': 3, 'c': 3})

most_common()

最も一般的な要素を降順で返す。

c = Counter('abbbccccd')
print(c.most_common())
# [('c', 4), ('b', 3), ('a', 1), ('d', 1)]

引数を指定すると、その数だけ要素を返す。

print(c.most_common(2))
# [('c', 4), ('b', 3)]

このように、Counter()は非常に便利な関数で、Python のコーディングにおいて頻繁に使用される。データ分析や情報処理の際には特に役立つツールである。

Python: カウンタ。Counter()関数で要素数を計算する