PythonのCounter – PythonのコレクションCounter

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

PythonのCounter

カウンターは、要素が辞書のキーとして格納され、その数が辞書の値として格納される順不同のコレクションです。カウンターの要素のカウントは、正の整数、ゼロ、または負の整数にすることができます。ただし、キーや値に制限はありません。値は数字を意図しているものですが、他のオブジェクトも格納することができます。

Python Counterオブジェクトを作成する

私たちは空のカウンターを作成することもできますし、初期値を持ってスタートすることもできます。

from collections import Counter

# empty Counter
counter = Counter()
print(counter)  # Counter()

# Counter with initial values
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オブジェクトを作成するために、任意のイテレータも引数として使用することができます。そのため、文字列リテラルやリストもCounterオブジェクトの作成に使用できます。

# Iterable as argument for Counter
counter = Counter('abc')
print(counter)  # Counter({'a': 1, 'b': 1, 'c': 1})

# List as argument to Counter
words_list = ['Cat', 'Dog', 'Horse', 'Dog']
counter = Counter(words_list)
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})

# Dictionary as argument to 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 works with non-numbers too
special_counter = Counter(name='Pankaj', age=20)
print(special_counter)  # Counter({'name': 'Pankaj', 'age': 20})

PythonのCounterメソッド

「Counterクラスのメソッドやそれに対する他の操作について見てみましょう。」

要素の数を取得する

# getting count
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
countDog = counter['Dog']
print(countDog)  # 2

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

# getting count for non existing key, don't cause KeyError
print(counter['Unicorn'])  # 0

要素の数を設定する

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

counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
# setting count
counter['Horse'] = 0
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

# setting count for non-existing key, adds to Counter
counter['Unicorn'] = 1
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})

カウンターから要素を削除する。

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

# Delete element from Counter
del counter['Unicorn']
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

要素()

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

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)

上記のコードは、「count」が2であるため、「Dog」という単語を2回出力します。他の要素は無視されます。カウンターは順序のないコレクションであり、要素は特定の順序で返されません。

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 = 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算術演算

私たちは数字と同様に、カウンター上でもいくつかの算術演算を行うことができます。ただし、これらの演算では正の個数を持つ要素のみが返されます。

# arithmetic operations
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({'a': 3, 'b': 3, 'c': 0})
# miscellaneous examples
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)])

# remove 0 or negative count elements
counter = Counter(a=2, b=3, c=-1, d=0)
counter = +counter
print(counter)  # Counter({'b': 3, 'a': 2})

# clear all elements
counter.clear()
print(counter)  # Counter()

PythonのCounterクラスに関する説明は以上です。

私のGitHubリポジトリから完全なサンプルコードをダウンロードすることができます。

参考文献:Pythonドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *