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

レベル 4163 打鍵

Counterを使用して要素の出現回数をカウントします。most_common()は要素とカウントを降順で返します。

Python のコード

# collectionsモジュールからCounterをインポートします
1from collections import Counter
2
# 繰り返しのある単語リストを作成します
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

Python のレベル 4 のほかのコード例

← Python タイピング練習のトップへ