📜  Python List.count()方法

📅  最后修改于: 2020-10-30 05:45:48             🧑  作者: Mango

Python清单count()方法

Python count()方法返回元素出现在列表中的次数。如果列表中不存在该元素,则返回0。下面将描述示例和语法。

签名

count(x)

参量

x:要计数的元素。

返回

它返回列表中出现x的次数。

我们来看一些count()方法的示例,以了解其功能。

Python列表count()方法示例1

这是了解计数方法如何工作的简单示例。

# Python list count() Method
# Creating a list
apple = ['a','p','p','l','e']
# Method calling
count = apple.count('p')
# Displaying result
print("count of p :",count)

输出:

count of p : 2

Python List count()方法示例2

如果列表中不存在传递的值,则该方法返回0。请参见下面的示例。

# Python list count() Method
# Creating a list
apple = ['a','p','p','l','e']
# Method calling
count = apple.count('b')
# Displaying result
print("count of b :",count)

输出:

count of b : 0

Python列表count()方法示例3

Python count()方法还可用于检查列表中元素是否重复。下面的示例检查列表中元素的重复性。

# Python list count() Method
# Creating a list
apple = ['a','p','p','l','e']
# Method calling
count = apple.count('p')
# Displaying result
if count>=2:
    print("value is duplicate")
print("count of p :",count)

输出:

value is duplicate
count of p : 2