Python の カウンターコレクション
レベル 4163 打鍵
Counterを使用して要素の出現回数をカウントします。most_common()は要素とカウントを降順で返します。
Python のコード
# collectionsモジュールからCounterをインポートします1from collections import Counter2 # 繰り返しのある単語リストを作成します3words = ["apple", "banana", "apple", "cherry", "banana", "apple"]# Counterは各要素の出現回数をカウントします4count = Counter(words)5 # 全てのカウントを表示するCounterオブジェクトを出力します6print(count)# 最も多い2つの要素とそのカウントを取得します7print(count.most_common(2))実行結果
Counter({'apple': 3, 'banana': 2, 'cherry': 1})
[('apple', 3), ('banana', 2)]このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この Python のコードで打つ記号と、出てくる回数です。
"× 12,× 5(× 4)× 4=× 2_× 1.× 1[× 1]× 1