Python count() 函数:统计序列元素出现的次数
Python 中的 count() 函数是用于统计列表、元组、字符串等序列中某个元素出现的次数。
my_list = [1, 2, 3, 2, 4, 2]
count_2 = my_list.count(2)
print(count_2) # 输出 3
使用方法:
count(element)
参数:
element: 要统计的元素
返回值:
- 元素在序列中出现的次数
示例:
my_string = 'hello world'
count_l = my_string.count('l')
print(count_l) # 输出 3
my_tuple = (1, 2, 3, 2, 4, 2)
count_2 = my_tuple.count(2)
print(count_2) # 输出 3
注意:
- count() 函数区分大小写。
- count() 函数只能用于统计序列中元素出现的次数,不能用于统计其他数据结构中的元素。
原文地址: https://www.cveoy.top/t/topic/gEiU 著作权归作者所有。请勿转载和采集!