Python 例付きリスト count()
⚡ スマートサマリー
その Python count() method returns how many times a given element appears in a list or string. Here you will learn its syntax, see examples on lists and strings, and count all elements at once with Counter.

Python カウント
count() は組み込み関数です。 Pythonリスト内の指定された要素の合計数を返します。count() 関数は、リストと文字列の要素をカウントするために使用されます。
Python リストカウント()
count() は組み込み関数です。 パイトン。 リスト内の特定の要素の数を返します。
構文
list.count(element)
技術パラメータ
素子: カウントを調べたい要素。
戻り値
count() メソッドは、整数値、つまり、指定されたリストからの指定された要素の数を返します。 値が指定されたリストに見つからない場合は 0 を返します。
例 1: リスト数
次の例は、リストでの count() 関数の動作を示しています。
list1 = ['red', 'green', 'blue', 'orange', 'green', 'gray', 'green']
color_count = list1.count('green')
print('The count of color: green is ', color_count)
出力:
The count of color: green is 3
例 2: 指定されたリスト内の要素 (重複) の数を見つける
list1 = [2,3,4,3,10,3,5,6,3]
elm_count = list1.count(3)
print('The count of element: 3 is ', elm_count)
出力:
The count of element: 3 is 4
Count Characters in a String
The count() method also works on strings, returning how many times a character or substring appears.
message = "hello world" print(message.count("l")) print(message.count("o"))
出力:
3 2
Count All Elements Using Counter
To count every element at once instead of one at a time, use Counter from the collections module.
from collections import Counter list1 = ["red", "green", "blue", "green", "red", "green"] print(Counter(list1))
出力:
Counter({'green': 3, 'red': 2, 'blue': 1})
