Python列表(list)元素出现次数

Python列表(list)元素出现次数教程

Python 中,我们需要统计一个元素在 列表 中出现的次数,使用 count 函数。

count函数详解

语法

listname.count(obj)

参数

参数 描述
listname 需要统计的列表。
obj 需要被统计的元素。

返回值

返回 obj 在列表中出现的次数。

说明

统计元素 obj 在列表 listname 中出现的次数。

案例

列表中元素出现次数

使用 count 函数,统计列表中元素出现次数

print("嗨客网(www.haicoder.net)") # 使用 count 函数,统计列表中元素出现次数 lis = ["Hello", "HaiCoder", 1024] count = lis.count("HaiCoder") print("Count =", count)

程序运行后,控制台输出如下:

27 python列表元素出现次数.png

我们使用 [] 创建了一个列表 lis,列表中有三个元素,接着,我们使用列表的 count 函数,统计元素 “HaiCoder” 在列表 lis 中出现的次数。

元素不存在

使用 count 函数,统计列表中不存在的元素出现次数

print("嗨客网(www.haicoder.net)") # 使用 count 函数,统计列表中不存在的元素出现次数 lis = ["Hello", "HaiCoder", 1024] count = lis.count("haicoder") print("Count =", count)

程序运行后,控制台输出如下:

28 python列表元素出现次数.png

使用 count 函数,统计列表中不存在的元素出现次数,返回 0。

Python列表(list)元素出现次数总结

在 Python 中,我们需要统计一个元素在列表中出现的次数,使用 count 函数。Python 列表(list) count 函数语法:

listname.count(obj)