使用 Python 程序统计元组中元素出现的次数


我们将了解如何统计元组中元素出现的次数。元组是一种不可变的 Python 对象序列。

假设我们有以下输入,其中检查 20 出现的次数 -

myTuple = (10, 20, 30, 40, 20, 20, 70, 80)

输出应为 -

Number of Occurrences of 20 = 3

使用 for 循环统计元组中元素出现的次数

在这个示例中,我们将统计元组中元素出现的次数 -

示例

def countFunc(myTuple, a): count = 0 for ele in myTuple: if (ele == a): count = count + 1 return count # Create a Tuple myTuple = (10, 20, 30, 40, 20, 20, 70, 80) # Display the Tuple print("Tuple = ",myTuple) # The element whose occurrence is to be checked k = 20 print("Number of Occurrences of ",k," = ",countFunc(myTuple, k))

输出

Tuple = (10, 20, 30, 40, 20, 20, 70, 80)
Number of Occurrences of 20 = 3

使用 count() 方法统计元组中元素出现的次数

在这个示例中,我们将统计元组中元素出现的次数 -

示例

def countFunc(myTuple, a): return myTuple.count(a) # Create a Tuple myTuple = (10, 20, 30, 70, 20, 20, 70, 80) # Display the Tuple print("Tuple = ",myTuple) # The element whose occurrence is to be checked k = 70 print("Number of Occurrences of ",k," = ",countFunc(myTuple, k))

输出

Tuple = (10, 20, 30, 70, 20, 20, 70, 80)
Number of Occurrences of 70 = 2

更新于: 11-Aug-2022

1K+ 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.