工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Python collections.Counter:効率的なカウント、更新、演算操作

Python collections.Counter:効率的なカウント、更新、演算操作

PythonのCounterは、イテラブル内の各要素の出現回数を数える特殊なコンテナです。dictを継承し、要素をキー、カウントを値として格納するため、ハッシュテーブル形式のカウントに最適です。

Python 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()の使用

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

まとめ

Python

  1. Python strip()メソッド完全ガイド:実践例付き
  2. Python str.count()マスター:文字と部分文字列のカウント実例集
  3. Python format()文字列を明確な例でマスター
  4. Python len()関数:オブジェクトの長さを測る実践ガイド
  5. Python String.find()メソッド完全ガイド:構文、例、代替手法
  6. Pythonラムダ関数をマスターする:実例とベストプラクティス
  7. Python round()関数を実例で徹底解説
  8. Python map()関数をマスター:構文、例、ベストプラクティス
  9. Python timeit():実行時間測定の実例付きガイド
  10. Python list.count() 完全ガイド:実践例付きで徹底解説
  11. Python list.index():要素の位置を検索する実践ガイド