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

例を使用したコレクション内の Python カウンター

Python カウンターとは

Python Counter は、コンテナー内に存在する各要素のカウントを保持するコンテナーです。カウンターは辞書クラス内で利用可能なサブクラスです。

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

Python カウンターを使用する理由

Python 3 Counter を使用する主な理由は次のとおりです。

この Python チュートリアルでは、次のことを学びます:

Python カウンターの紹介

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

構文:

Counter(list)

次のリストがあるとします:

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

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

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

文字列でカウンター

Python では、すべてがオブジェクトであり、文字列もオブジェクトです。 Python 文字列は、文字を二重引用符で囲むだけで作成できます。 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 は、指定されたタプルの各要素の数を返します。

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

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

出力:

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

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

カウンターを初期化しています

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

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() メソッドを使用して、カウンタに値を追加できます。

_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 Counter での算術演算

以下の例に示すように、加算、減算、積、和などの算術演算を Counter で実行できます。

例:

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 で使用できる重要なメソッドがいくつかあります。同じリストを次に示します。

例:elements()

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

まとめ:


Python

  1. 例を使用した Python 文字列 strip() 関数
  2. 例を使用した Python 文字列 count()
  3. Python String format() 例で説明
  4. Python 文字列の長さ | len() メソッドの例
  5. Python String find() メソッドと例
  6. 例を含む Python Lambda 関数
  7. 例を使用した Python round() 関数
  8. 例を使用した Python map() 関数
  9. Python Timeit() と例
  10. 例を使用した Python List count()
  11. Python List index() と例