前言:count()
是Python中用于序列类型(如列表、元组、字符串等)的内置方法,用于统计某个元素在序列中出现的次数。
sequence.count(x)
sequence
:可以是列表、元组或字符串等序列x
:要统计的元素x
在序列中出现的次数(整数)fruits = ['apple', 'banana', 'orange', 'apple', 'pear', 'apple']
# 统计'apple'出现的次数
apple_count = fruits.count('apple')
print(apple_count) # 输出: 3
# 统计不存在的元素
melon_count = fruits.count('melon')
print(melon_count) # 输出: 0
numbers = (1, 2, 3, 4, 2, 5, 2, 6)
# 统计数字2出现的次数
two_count = numbers.count(2)
print(two_count) # 输出: 3
sentence = "I love Python, Python is awesome!"
# 统计'Python'出现的次数
python_count = sentence.count('Python')
print(python_count) # 输出: 2
# 统计单个字符'o'出现的次数
o_count = sentence.count('o')
print(o_count) # 输出: 4
count()
方法还可以接受可选的起始和结束位置参数:
sequence.count(x, start, end)
start
:开始搜索的索引(包含)end
:结束搜索的索引(不包含)示例:
data = [1, 2, 3, 4, 2, 5, 2, 6]
print(data.count(2, 1, 6)) # 从索引1到5: [2,3,4,2,5] → 2出现2次
# ! 注意,这样会报错,呜呜呜
Python 之count()报错
对于包含复杂元素的序列(如列表的列表),count()
会进行严格匹配:
matrix = [[1, 2], [3, 4], [1, 2], [5, 6]]
# 统计[1, 2]出现的次数
count = matrix.count([1, 2])
print(count) # 输出: 2
count()
方法是区分大小写的:
"Python".count("p") # 返回0,因为大小写不匹配
对于自定义对象,count()
使用==
运算符进行比较:
class Person:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
people = [Person("Alice"), Person("Bob"), Person("Alice")]
print(people.count(Person("Alice"))) # 输出: 2
count()应用中代码解析
count()
的时间复杂度为O(n),因为它需要遍历整个序列。总结:count()
是一个简单但实用的方法,特别适合需要快速统计元素出现次数的场景。