Python コレクション内のカウンターの例

⚡ スマートサマリー

Python Counterは、コレクションモジュールの辞書サブクラスであり、反復可能なオブジェクト内で各要素が出現する回数をカウントします。文字列、リスト、タプル、辞書を受け入れ、高速なカウント処理のために算術演算、最頻値演算、更新操作をサポートしています。

  • 🔢 カウント: カウンターは各要素の出現回数を集計し、キーと出現回数のペアとして返します。
  • 📥 任意の反復可能オブジェクト: 入力として、文字列、リスト、タプル、辞書を受け付けます。
  • 算術: カウンターは加算、減算をサポートしますtrac結合、交差、および結合操作。
  • ???? 最も一般的(): このメソッドは、出現頻度の高い要素を順位付けして返します。
  • 🔄 アップデート: update() と subtract() は、別のカウンターまたはイテラブルからカウントを調整します。
  • 🤖 AIによる支援: AIアシスタントはカウンターコードを生成し、頻度や単語数のカウントといったタスクに提案します。

Python コレクションのカウンター

何ですか Python カウンタ?

Python カウンターは、コンテナー内に存在する各要素の数を保持するコンテナーです。カウンターは、辞書クラス内で使用できるサブクラスです。

カウンターは辞書クラス内で利用可能なサブクラスです。 Python カウンター ツールを使用すると、ハッシュ テーブル オブジェクトとも呼ばれるオブジェクト内のキーと値のペアをカウントできます。

なぜ使用 Python カウンタ?

以下は、使用する主な理由です。 Python 3 カウンター:

  • Counter は、ハッシュテーブル オブジェクトと同様に、順序付けされていないコレクションにデータを保持します。 ここでの要素は、キーとカウントを値として表します。
  • これを使用すると、反復可能なリスト内の項目をカウントできます。
  • 加算、減算などの算術演算tracカウンター上では、結合、積集合、和集合を簡単に実行できます。
  • カウンタは別のカウンタの要素をカウントすることもできます

はじめに Python カウンター

Python Counter は、反復可能なオブジェクトであるリスト、タプル、辞書、文字列を入力として受け取り、各要素のカウントを含む出力を返します。

構文:

Counter(list)

次のようなリストがあるとします。

list1 = ['x','y','z','x','x','x','y', 'z']

リストには要素 x 、 y 、 z があります。このリストで Counter を使用すると、 x 、 y 、 z が存在する回数がカウントされます。 list1 でカウンタが使用されている場合の出力は次のようになります。

Counter({'x': 4, 'y': 2, 'z': 2})

したがって、x は 4、y は 2、z は 2 となります。

Counter を使用するには、以下の例に示すように、最初にカウンターをインポートする必要があります。

from collections import Counter

これは、Counter モジュールの動作を示す簡単な例です。

from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))

出力:

Counter({'x': 4, 'y': 2, 'z': 2})

文字列付きカウンター

In Pythonすべてがオブジェクトであり、文字列もオブジェクトです。 Python string 文字を二重引用符で囲むだけで作成できます。 Python 文字型をサポートしていません。これらは長さ 1 の文字列として扱われ、部分文字列としても扱われます。

以下の例では、文字列が Counter に渡されます。 キーが要素で値がカウントであるキーと値のペアを含む辞書形式を返します。 また、スペースを要素として考慮し、文字列内のスペースの数を示します。

例:

from collections import Counter
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})

リスト付きカウンター

リストは、要素が角括弧で囲まれた反復可能なオブジェクトです。

リスト内の要素は、Counter に渡されるとハッシュテーブル オブジェクトに変換され、要素はキーになり、値は指定されたリストの要素の数になります。

たとえば、['x','y','z','x','x','x','y','z']。 リストにカウンターを指定すると、リスト内の各要素の数が表示されます。

from collections import Counter
list1 = ['x','y','z','x','x','x','y','z']
print(Counter(list1))

出力:

Counter({'x': 4, 'y': 2, 'z': 2})

辞書付きカウンター

辞書にはキーと値のペアとして要素があり、それらは中括弧内に記述されます。

ディクショナリが Counter に渡されると、要素がキーとなるハッシュテーブル オブジェクトに変換され、値は指定されたディクショナリからの要素の数になります。

例: {'x': 4, 'y': 2, 'z': 2, 'z': 2}。 Counter 関数は、指定された辞書内の各キーの数を見つけようとします。

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2, 'z': 2}
print(Counter(dict1))

出力:

Counter({'x': 4, 'y': 2, 'z': 2})

タプルによるカウンター

タプルは、丸括弧内のカンマで区切られたオブジェクトのコレクションです。カウンターは、指定されたタプル内の各要素の数を表示します。

タプルが Counter に渡されると、ハッシュテーブル オブジェクトに変換され、要素がキーになり、値は指定されたタプルの要素の数になります。

from collections import Counter
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))

出力:

Counter({'x': 4, 'y': 2, 'z': 2})

カウンタへのアクセス、初期化、および更新

カウンタの初期化中

以下に示すように、文字列値、リスト、辞書、またはタプルを渡すことでカウンターを初期化できます。

from collections import Counter
print(Counter("Welcome to Guru99 Tutorials!"))   #using string
print(Counter(['x','y','z','x','x','x','y', 'z'])) #using list
print(Counter({'x': 4, 'y': 2, 'z': 2})) #using dictionary
print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple

以下に示すように、空のカウンターを初期化することもできます。

from collections import Counter
_count = Counter()

カウンタを更新しています

update() メソッドを使用して、Counter に値を追加できます。

_count.update('Welcome to Guru99 Tutorials!')

最終的なコードは次のとおりです。

from collections import Counter
_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})

アクセスカウンター

カウンタから値を取得するには、次のように実行できます。

from collections import Counter

_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print('%s : %d' % ('u', _count['u']))
print('\n')
for char in 'Guru':
    print('%s : %d' % (char, _count[char]))

出力:

u : 3

G : 1
u : 3
r : 2
u : 3

カウンタからの要素の削除

Counter から要素を削除するには、以下の例に示すように、 del を使用できます。

例:

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2}
del dict1["x"]
print(Counter(dict1))

出力:

Counter({'y': 2, 'z': 2})

算術演算 Python カウンター

加算、減算などの算術演算tracカウンター上では、以下の例に示すように、結合、積集合、和集合を計算できます。

例:

from collections import Counter
counter1 =  Counter({'x': 4, 'y': 2, 'z': -2})

counter2 = Counter({'x1': -12, 'y': 5, 'z':4 })

#Addition
counter3 = counter1 + counter2 # only the values that are positive will be returned.

print(counter3)

#Subtraction
counter4 = counter1 - counter2 # all -ve numbers are excluded.For example z will be z = -2-4=-6, since it is -ve value it is not shown in the output

print(counter4)

#Intersection
counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2

print(counter5)

#Union
counter6 = counter1 | counter2 # it will give positive max values from counter1 and counter2

print(counter6)

出力:

Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})

利用可能な方法 Python カウンター

Counter で利用できる重要なメソッドがいくつかあります。以下にそのリストを示します。

  • 要素() : このメソッドは、カウント >0 のすべての要素を返します。 カウントが 0 または -1 の要素は返されません。
  • most_common(値): このメソッドは、カウンター リストから最も一般的な要素を返します。
  • 以下tract(): このメソッドは、別のカウンターから要素を差し引くために使用されます。
  • アップデート(): このメソッドは、別のカウンターから要素を更新するために使用されます。

例: 要素()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 2, 'z': -2, 'x1':0})

_elements = counter1.elements() # will give you all elements with positive value and count>0
for a in _elements:
    print(a)

出力:

x
x
x
x
x
y
y

例: most_common(値)

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

common_element = counter1.most_common(2) # The dictionary will be sorted as per the most common element first followed by next.
print(common_element)

common_element1 = counter1.most_common() # if the value is not given to most_common , it will sort the dictionary and give the most common elements from the start.The last element will be the least common element.
print(common_element1)

出力:

 [('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]

例: subtract()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})

counter1.subtract(counter2)
print(counter1)

出力:

Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})

例: update()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.update(counter2)
print(counter1)

出力:

Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})

カウントの再割り当て Python

以下に示すように、カウンターのカウントを再割り当てできます。

{'x': 5, 'y': 12, 'z': -2, 'x1':0} のような辞書があるとします。

以下に示すように、要素の数を変更できます。

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

counter1['y'] = 20

print(counter1)

出力: 実行後、y カウントが 12 から 20 に変更されることがわかります。

Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})

Counter を使用して要素数を取得および設定する

Counter を使用して要素の数を取得するには、次のように実行できます。

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
print(counter1['y']) # this will give you the count of element 'y'

出力:

12

要素の数を設定するには、次のように実行できます。

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

print(counter1['y'])

counter1['y'] = 20
counter1['y1'] = 10

print(counter1)

出力:

12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})

よくあるご質問

Counter は、ハッシュ可能な項目を自動的にカウントし、キーが見つからない場合は KeyError を発生させる代わりに 0 を返す dict のサブクラスです。通常の辞書では手動でカウントするロジックが必要で、キーが見つからない場合は KeyError が発生します。

most_common(n) は、出現頻度の高い順に、n 個の要素を (要素, 出現回数) のタプルとして返します。引数を指定せずに呼び出すと、出現回数順にすべての要素が返されます。

以下tract() は、減算後にゼロと負のカウントを保持し、カウンターをその場で変更します。マイナス演算子は新しいカウンターを返し、結果がゼロまたは負になる要素を削除します。

はい。単語単位でカウントするには、まずテキストを分割してください(例:Counter(sentence.split()))。生の文字列を渡すと、単語ではなく、スペースを含む個々の文字がカウントされます。

すべてのカウントを加算するには sum(counter.values()) を使用するか、または Counter.total() を使用します。 Python バージョン3.10以降。これは、カウンターがこれまでにカウントした要素の総数を示します。

カウンターは__missing__を上書きするため、存在しない要素はすべてカウント0として報告されます。これにより、要素が存在するかどうかを事前に確認することなく、新しいキーをインクリメントしたり、要素をクエリしたりすることが安全に行えます。

AIアシスタントは、頻度分析のためのカウンターコードを生成し、手動ループよりもカウンターの使用を推奨し、most_commonやelementsといったメソッドを説明します。また、カウントロジックをより簡潔で高速なコレクションベースのコードに変換します。

はい。GitHub Copilotは、目的を説明するコメントからCounter、defaultdict、OrderedDictのパターンを自動補完します。Agentic AIツールは、手動でカウントするループをCounter呼び出しにリファクタリングし、ファイル全体にテストを追加します。