📌  相关文章
📜  Python|计算元组中元素的出现次数

📅  最后修改于: 2022-05-13 01:55:25.092000             🧑  作者: Mango

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

在这个程序中,我们需要接受一个元组,然后找到一个项目在元组中出现的次数。这可以通过多种方式完成,但在本文中,我们将看到如何使用简单的方法来完成,以及如何使用内置函数来解决这个问题。

例子:

Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)

Input : 4
Output : 0 times

Input : 10
Output : 3 times

Input : 8
Output : 4 times

方法1(简单方法):
如果在元组中找到所需的元素,我们会保持一个不断增加的计数器。

# Program to count the number of times an element
# Present in the list
def countX(tup, x):
    count = 0
    for ele in tup:
        if (ele == x):
            count = count + 1
    return count
   
# Driver Code
tup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
enq = 4
enq1 = 10
enq2 = 8
print(countX(tup, enq))
print(countX(tup, enq1))
print(countX(tup, enq2))

输出:

0 times
3 times
4 times

方法2(使用count()):
这个想法是使用方法 count() 来计算出现次数。

# Program to count the number of times an element
# Present in the list
# Count function is used
def Count(tup, en):
    return tup.count(en)
  
# Driver Code
tup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
enq = 4
enq1 = 10
enq2 = 8
print(Count(tup, enq), "times")
print(Count(tup, enq1), "times")
print(Count(tup, enq2), "times")

输出:

0 times
3 times
4 times