使用 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.