Python List count() メソッド

Python List count() メソッド リスト内の指定された要素の出現数を返します。

例:

Python3




#create a list> fruits> => [> 'Apple'> ,> 'Mango'> ,> 'Banana'> ,> 'Cherry'> ,> 'Papaya'> ]> # printing count using count() function> print> (fruits.count(> 'Apple'> ))>

出力

1 

list count() メソッドとは何ですか?

list count() 関数 パイソン は、リスト内の要素の出現をカウントできる組み込み関数です。要素がリスト内に何回存在するかを返します。

使い方次第で様々な応用が可能です。例: いずれかの要素の数が 1 より大きい場合、値が重複していることを意味します。 count が 0 の場合、その要素がリストに存在しないことを意味します。そのため、使い方次第でさまざまな用途に活用できます。

パラメータを 1 つだけ受け入れます。複数のパラメータを渡すと発生します。 タイプエラー。

List count() メソッドの構文

リスト名.カウント(オブジェクト)

パラメーター:

  • 物体: カウントが返される項目です。

戻り値:

リスト内でオブジェクトが出現した回数を返します。

List count() 関数の使用方法

list count() 関数は非常に使いやすい関数です。必要なのは、オブジェクト リストを指定して count() 関数を呼び出し、関数内のパラメーターとして要素を渡すことだけです。

簡単な例を使用して、リスト内の要素の出現をカウントする方法をより深く理解しましょう。

Python3




#creating a list> Rand> => [> 1> ,> 3> ,> 2> ,> 4> ,> 1> ,> 3> ,> 2> ,> 4> ,> 5> ,> 2> ,> 3> ]> #lets count occurence of 2> print> (Rand.count(> 2> ))>

出力

3 

List count() メソッドのその他の例

count() メソッドのさまざまな使用例のいくつかについて説明しましょう。

例:

Python3




list2> => [> 'a'> ,> 'a'> ,> 'a'> ,> 'b'> ,> 'b'> ,> 'a'> ,> 'c'> ,> 'b'> ]> print> (list2.count(> 'b'> ))>

出力

3 

リスト内のタプルとリスト要素をカウントする

List と Python タプル Python count() メソッドを使用してリスト内で。

Python3




list1> => [ (> 'Cat'> ,> 'Bat'> ), (> 'Sat'> ,> 'Cat'> ), (> 'Cat'> ,> 'Bat'> ),> > (> 'Cat'> ,> 'Bat'> ,> 'Sat'> ), [> 1> ,> 2> ], [> 1> ,> 2> ,> 3> ], [> 1> ,> 2> ] ]> # Counts the number of times 'Cat' appears in list1> print> (list1.count((> 'Cat'> ,> 'Bat'> )))> # Count the number of times sublist> # '[1, 2]' appears in list1> print> (list1.count([> 1> ,> 2> ]))>

出力

2 2 

Python list count() メソッド使用時の例外

count() 関数の使用中に発生する可能性のあるいくつかのエラーについても説明します。

TypeError: count() は引数を 1 つだけ取ります

Python の List count() では、複数のパラメーターが渡されると TypeError が発生します。

Python3




list1> => [> 1> ,> 1> ,> 1> ,> 2> ,> 3> ,> 2> ,> 1> ]> # Error when two parameters is passed.> print> (list1.count(> 1> ,> 2> ))>

出力:

Traceback (most recent call last):  File '/home/41d2d7646b4b549b399b0dfe29e38c53.py', line 7, in   print(list1.count(1, 2))  TypeError: count() takes exactly one argument (2 given) 

実用化

内の各要素をカウントしたいとします。 Python リスト それを別のリストに保存するか、 Python辞書

Python3




# Python3 program to count the number of times> # an object appears in a list using count() method> lst> => [> 'Cat'> ,> 'Bat'> ,> 'Sat'> ,> 'Cat'> ,> 'Mat'> ,> 'Cat'> ,> 'Sat'> ]> # To get the number of occurrences> # of each item in a list> print> ([ [l, lst.count(l)]> for> l> in> set> (lst)])> # To get the number of occurrences> # of each item in a dictionary> print> (> dict> ( (l, lst.count(l) )> for> l> in> set> (lst)))>

出力

[['Mat', 1], ['Sat', 2], ['Bat', 1], ['Cat', 3]] {'Mat': 1, 'Sat': 2, 'Bat': 1, 'Cat': 3} 

list count() メソッドの定義、構文、例について説明しました。また、さまざまな例外と関数の実際の例についても説明しました。

list count() メソッドはリスト操作の非常に基本的な関数であり、使用は非常に簡単です。

続きを読む: Python リスト メソッド

こちらもお読みください: