Python 计算元组中元素出现次数

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程