在Python中,`count`函数用于统计某个元素在字符串或列表中出现的次数。以下是`count`函数的基本用法:
字符串中的`count`函数
```python
str.count(sub, start=0, end=len(str))`
`str`:要搜索的字符串。
`sub`:要搜索的子字符串。
`start`:搜索的起始位置,默认为0。
`end`:搜索的结束位置,默认为字符串的长度。
列表中的`count`函数
list.count(obj)`
`list`:要搜索的列表。
`obj`:要搜索的元素。
示例
字符串中的`count`函数示例
```python
text = "this is a string example"
print(text.count("is")) 输出:2
print(text.count("a", 2, 10)) 输出:1
print(text.count("x")) 输出:0
列表中的`count`函数示例
```python
numbers = [1, 2, 3, 4, 5, 5, 6, 7, 5, 8, 9, 5]
print(numbers.count(5)) 输出:4
print(numbers.count(10)) 输出:0
`count`函数的时间复杂度为O(n),其中n为字符串或列表的长度。当处理大型数据集时,应注意效率问题。