用于计算元组中元素出现次数的 Python 程序

programmingpythonserver side programming

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

假设我们有以下输入,需要检查出现次数为 20 次 −

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

输出应为 −

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() 方法计算 Tuple 中元素的出现次数

在此示例中,我们将计算 Tuple 中元素的出现次数 −

示例

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

相关文章