Python のカウンター |セット 2 (カウンターへのアクセス)
Python のカウンター |セット 1 (初期化と更新)
Python のカウンター |セット2
初期化されたカウンタは、辞書と同様にアクセスされます。また、KeyValue エラー (キーが存在しない場合) は発生せず、代わりに値のカウントが 0 として表示されます。
例: この例では使用しています カウンタ キーとそのキーの頻度を出力します。周波数マップ内に存在する要素はその周波数とともに出力され、要素がカウンター マップ内に存在しない場合、要素は 0 とともに出力されます。
Python3 from collections import Counter # Create a list z = [ 'blue' 'red' 'blue' 'yellow' 'blue' 'red' ] col_count = Counter ( z ) print ( col_count ) col = [ 'blue' 'red' 'yellow' 'green' ] # Here green is not in col_count # so count of green will be zero for color in col : print ( color col_count [ color ])
出力: < Counter({'blue': 3 'red': 2 'yellow': 1}) blue 3 red 2 yellow 1 green 0Python の Counter の elements() メソッド
elements() メソッドは、Counter が認識しているすべての項目を生成する反復子を返します。注: カウントのある要素 <= 0 are not included.
例 : この例では、Counter 内の要素は、Counter の elements() メソッドを使用して出力されます。
Python3出力:# Python example to demonstrate elements() from collections import Counter coun = Counter ( a = 1 b = 2 c = 3 ) print ( coun ) print ( list ( coun . elements ()))Counter({'c': 3 'b': 2 'a': 1}) ['a' 'b' 'b' 'c' 'c' 'c']Python の Counter の most_common() メソッド
most_common() は、最も頻繁に発生する n 個の入力値とそのそれぞれのカウントのシーケンスを生成するために使用されます。パラメータ「n」が指定されていないか、パラメータとして None が渡された場合、most_common() はすべての要素とその数のリストを返します。
例: この例では、Python の Counter 内の most_common() メソッドを使用して、最も頻度の高い要素が出力され、続いて次に頻度の高い要素が出力されます。
Python3出力:from collections import Counter coun = Counter ( a = 1 b = 2 c = 3 d = 120 e = 1 f = 219 ) # This prints 3 most frequent characters for letter count in coun . most_common ( 3 ): print ( ' %s : %d ' % ( letter count ))f: 219 d: 120 c: 3