python numpy 计数 python中如何计数_字符串



Python列表计数count()方法


count()是Python中的内置函数。 它将返回列表中给定元素的总数。 count()函数用于对列表中的元素以及字符串进行计数。



在此Python教程中,我们将学习:

  • Python计数count()方法
  • Python列表count()方法


语法:

list.count(element)

参数:

element:是我们要查找计数的元素.

返回值:

count()方法将返回一个整数值,即给定列表中给定元素的计数。 如果在给定列表中找不到该值,则返回0.


示例1:列表计数

以下示例显示了list()函数的工作方式:

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

摘要:

  1. count()是Python中的内置函数。 它将返回列表或字符串中给定元素的个数。
  2. 对于列表,需要将计数的元素传递给count()函数,它将返回该元素的个数。
  3. count()方法返回一个整数值。