Python 列出 count() 和示例

Python 数

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

Python 列表计数()

count() 是 皮顿。它将返回列表中给定元素的数量。

句法

list.count(element)

参数

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() 是 Python. 它将返回列表或字符串中给定元素的数量。
  • 对于列表,需要将要计数的元素提供给 count() 函数,它将返回该元素的计数。
  • count() 方法返回一个整数值。