python 中的count()
函數有助于返回元組中給定元素的出現次數。元組是一種內置的數據類型,用于存儲多個元素,它是有序且不可更改的。
**tuple.count(element)** #where element may be a integer,string,etc.
計數()參數:
count()
函數接受一個參數。如果參數丟失,它將返回一個錯誤。
參數 | 描述 | 必需/可選 |
---|---|---|
元素 | 要計數的元素 | 需要 |
計數()返回值
返回值始終是一個整數,它指示特定元素在元組中出現的次數。如果元組中沒有給定的元素,它將返回零。
| 投入 | 返回值 | | 元素 | 整數(計數) |
Python 中count()
方法的示例
示例 1:元組計數()在皮托中是如何工作的?
# vowels tuple
alphabets = ('a', 'b', 'c', 'd', 'a', 'b')
# count element 'a'
count = alphabets .count('a')
# print count
print('The count of a is:', count)
# count element 'c'
count = alphabets .count('c')
# print count
print('The count of c is:', count)
輸出:
The count of a is: 2
The count of c is: 1
示例 2:如何統計 tuple 中的列表和 Tuple 元素?
# random tuple
random_tup = ('a', ('b', 'c'), ('b', 'c'), [1, 2])
# count element ('b', 'c')
count = random_tup.count(('b', 'c'))
# print count
print("The count of ('b', 'c') is:", count)
# count element [1, 2]
count = random_tup.count([1, 2])
# print count
print("The count of [1, 2] is:", count)
輸出:
The count of ('b', 'c') is: 2
The count of [1, 2] is: 1