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() 方法也适用于字符串,返回字符或子字符串出现的次数。
message = "hello world" print(message.count("l")) print(message.count("o"))
输出:
3 2
使用计数器统计所有元素
要一次性统计所有元素而不是逐个统计,请使用 collections 模块中的 Counter 函数。
from collections import Counter list1 = ["red", "green", "blue", "green", "red", "green"] print(Counter(list1))
输出:
Counter({'green': 3, 'red': 2, 'blue': 1})
