Python List count() 示例
Python count
count() 是 Python 的内置函数。它会返回列表中给定元素的总数。count() 函数用于计算列表和字符串中的元素数量。
Python List count()
count() 是 Python 的内置函数。它将返回列表中给定元素的计数。
语法
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() 方法返回一个整数值。