Python count() 方法:统计元素出现次数
Python 的 count() 方法是用于统计字符串、列表等对象中某个元素出现的次数。它接受一个参数,即要统计的元素,返回值为该元素在对象中出现的次数。
例如,以下代码统计字符串 'hello world' 中字母 'l' 出现的次数:
string = 'hello world'
count = string.count('l')
print(count) # 输出结果为 3
count() 方法还可以用于统计列表中某个元素出现的次数:
list = [1, 2, 3, 2, 4, 2]
count = list.count(2)
print(count) # 输出结果为 3
count() 方法是一个非常常用的方法,可以用于各种数据分析和统计工作。
原文地址: https://www.cveoy.top/t/topic/l1OK 著作权归作者所有。请勿转载和采集!