Python Counter – Python Collections Counter

PythonのCounterクラスは、Collectionsモジュールの一部です。CounterはDictionaryのサブクラスであり、要素とその数を追跡するために使用されます。

Python Counter

Counterは要素がDictのキーとして、その数がdict値として保存される順序付けされていないコレクションです。Counterの要素の数は正の整数、ゼロ、または負の整数である可能性があります。ただし、そのキーと値に制限はありません。値は数値であることが意図されていますが、他のオブジェクトも格納できます。

Python Counterオブジェクトの作成

空のCounterを作成するか、いくつかの初期値を指定して開始することができます。

from collections import Counter

# 空のCounter
counter = Counter()
print(counter)  # Counter()

# 初期値を持つCounter
counter = Counter(['a', 'a', 'b'])
print(counter)  # Counter({'a': 2, 'b': 1})

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

Counterオブジェクトを作成するための引数として任意のIterableを使用することもできます。したがって、文字列リテラルリストもCounterオブジェクトの作成に使用できます。

# Counterの引数としてイテラブルを使用する
counter = Counter('abc')
print(counter)  # Counter({'a': 1, 'b': 1, 'c': 1})

# Counterの引数としてリストを使用する
words_list = ['Cat', 'Dog', 'Horse', 'Dog']
counter = Counter(words_list)
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})

# Counterの引数として辞書を使用する
word_count_dict = {'Dog': 2, 'Cat': 1, 'Horse': 1}
counter = Counter(word_count_dict)
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})

前述のように、カウント値には非数値データも使用できますが、それはCounterクラスの目的に反します。

# Counterは非数値でも機能します
special_counter = Counter(name='Pankaj', age=20)
print(special_counter)  # Counter({'name': 'Pankaj', 'age': 20})

PythonのCounterメソッド

Counterクラスのメソッドとそれに対して行えるその他の操作について見ていきましょう。

要素のカウントを取得する

# カウントの取得
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
countDog = counter['Dog']
print(countDog)  # 2

存在しないキーのカウントを取得しようとすると、0が返され、KeyErrorは発生しません。

# 存在しないキーのカウントの取得は、KeyErrorを発生させません
print(counter['Unicorn'])  # 0

要素のカウントを設定する

カウンター内の既存の要素のカウントを設定することもできます。要素が存在しない場合は、カウンターに追加されます。

counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
# カウントの設定
counter['Horse'] = 0
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

# カウントの設定 for non-existing key, adds to Counter
counter['Unicorn'] = 1
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})

Counterから要素を削除する

カウンターオブジェクトから要素を削除するにはdelを使用できます。

# カウンターから要素を削除
del counter['Unicorn']
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

elements()

このメソッドは、カウンター内の要素のリストを返します。正のカウントを持つ要素のみが返されます。

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})

# elements()
elements = counter.elements()  # doesn't return elements with count 0 or less
for value in elements:
    print(value)

上記のコードは、「Dog」が2回出力されます。そのカウントが2であるためです。他の要素は正のカウントを持っていないため、無視されます。カウンターは順序付けられていないコレクションなので、要素は特定の順序で返されます。

most_common(n)

このメソッドは、カウンターから最も一般的な要素を返します。 ‘n’の値を指定しない場合、最も一般的な要素から最も一般的でない要素までのソートされた辞書が返されます。このソートされた辞書から最も一般的でない要素を取得するためにスライスを使用できます。

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})

# most_common()
most_common_element = counter.most_common(1)
print(most_common_element)  # [('Dog', 2)]

least_common_element = counter.most_common()[:-2:-1]
print(least_common_element)  # [('Cat', -1)]

subtract() および update()

Counter subtract() メソッドは、別のカウンターから要素の数を減算するために使用されます。 update() メソッドは、別のカウンターからカウントを追加するために使用されます。

counter = Counter('ababab')
print(counter)  # Counter({'a': 3, 'b': 3})
c = Counter('abc')
print(c)  # Counter({'a': 1, 'b': 1, 'c': 1})

# subtract
counter.subtract(c)
print(counter)  # Counter({'a': 2, 'b': 2, 'c': -1})

# update
counter.update(c)
print(counter)  # Counter({'a': 3, 'b': 3, 'c': 0})

Python の Counter 算術演算

私たちは、数値のように Counters 上でいくつかの算術演算を実行することもできます。ただし、これらの操作では正のカウントの要素のみが返されます。

# 算術演算
c1 = Counter(a=2, b=0, c=-1)
c2 = Counter(a=1, b=-1, c=2)

c = c1 + c2  # return items having +ve count only
print(c)  # Counter({'a': 3, 'c': 1})

c = c1 - c2  # keeps only +ve count elements
print(c)  # Counter({'a': 1, 'b': 1})

c = c1 & c2  # intersection min(c1[x], c2[x])
print(c)  # Counter({'a': 1})

c = c1 | c2  # union max(c1[x], c2[x])
print(c)  # Counter({'a': 2, 'c': 2})

Python の Counter に関するその他の操作

Counter オブジェクト上で実行できるその他の操作について、いくつかのコードスニペットを見てみましょう。

counter = Counter({'a': 3, 'b': 3, 'c': 0})
# その他の例
print(sum(counter.values()))  # 6

print(list(counter))  # ['a', 'b', 'c']
print(set(counter))  # {'a', 'b', 'c'}
print(dict(counter))  # {'a': 3, 'b': 3, 'c': 0}
print(counter.items())  # dict_items([('a', 3), ('b', 3), ('c', 0)])

# 0 または負のカウントの要素を削除
counter = Counter(a=2, b=3, c=-1, d=0)
counter = +counter
print(counter)  # Counter({'b': 3, 'a': 2})

# すべての要素をクリア
counter.clear()
print(counter)  # Counter()

これで Python の Counter クラスについての説明は終わりです。

完全な例コードは、私の GitHub リポジトリ からダウンロードできます。

参考: Pythonドキュメント

Source:
https://www.digitalocean.com/community/tutorials/python-counter-python-collections-counter