使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP