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

Python list.count() 完全ガイド:実践例付きで徹底解説

list.count()とは

Pythonの組み込みメソッドlist.count()は、指定した要素がリスト内に何回出現するかを返します。文字列でも動作するため、データ分析、テキスト処理など幅広い用途で使える汎用的なツールです。

動作仕様

構文: list_obj.count(element)

パラメータ: element – 出現回数を数えたい値。

戻り値: 出現回数を表す整数。要素が存在しない場合は0。

例1:リスト内の色のカウント

colors = ['red', 'green', 'blue', 'orange', 'green', 'gray', 'green']
green_count = colors.count('green')
print('The count of green:', green_count)

出力:

The count of green: 3

例2:重複数値のカウント

numbers = [2, 3, 4, 3, 10, 3, 5, 6, 3]
threes = numbers.count(3)
print('The count of 3:', threes)

出力:

The count of 3: 4

list.count()を使う場面

パフォーマンス補足

このメソッドはリスト全体をスキャンするため、時間計算量はO(n)です。大規模データセットで複数要素をカウントする場合はcollections.Counterの利用を検討してください。

まとめ

Python

  1. Python print()関数の実践ガイド:基本から応用まで
  2. Python str.count()マスター:文字と部分文字列のカウント実例集
  3. Python format()文字列を明確な例でマスター
  4. Python String.find()メソッド完全ガイド:構文、例、代替手法
  5. Pythonラムダ関数をマスターする:実例とベストプラクティス
  6. Python round()関数を実例で徹底解説
  7. Python range()関数をマスター:基礎から応用まで
  8. Python map()関数をマスター:構文、例、ベストプラクティス
  9. Python timeit():実行時間測定の実例付きガイド
  10. Python collections.Counter:効率的なカウント、更新、演算操作
  11. Python type()とisinstance()の理解:実例付き解説