Python元祖(tuple)元素出现次数

Python元祖(tuple)元素出现次数教程

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

count函数详解

语法

tuplename.count(obj)

参数

参数 描述
tuplename 需要统计元素个数的元祖。
obj 需要统计的元素。

返回值

返回元素 obj 在元祖中出现的次数。

说明

统计元素 obj 在元祖 tuplename 中出现的次数。

案例

元祖中元素出现次数

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

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

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

78 python元祖元素出现次数.png

我们使用 () 创建了一个元祖 tup,元祖中有三个元素,接着,我们使用元祖的 count 函数,统计元素 “HaiCoder” 在元祖 tup 中出现的次数。

元素不存在

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

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

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

79 python元祖元素出现次数.png

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

Python元祖(tuple)元素出现次数总结

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

tuplename.count(obj)