跳至主要内容

count()

Python 中的 count() 方法用于统计列表中指定元素出现的次数。它返回指定元素在列表中出现的次数。

参数值

参数 说明
element

要统计的列表元素。

返回值

Python 中的 List 中的 count() 方法返回一个 int

如何在 Python 中使用 count()

示例 1

count() 方法返回指定值在列表中出现的次数。

numbers = [1, 2, 3, 1, 4, 1, 5]
print(numbers.count(1)) # Output: 3
示例 2

它可用于列表中的任何类型的元素,而不仅仅是 整数

fruits = ['apple', 'banana', 'orange', 'apple']
print(fruits.count('apple')) # Output: 2
示例 3

如果指定的值不在列表中,则返回 0。

colors = ['red', 'blue', 'green']
print(colors.count('yellow')) # Output: 0