count()方法返回元組中元素出現(xiàn)的次數(shù)。
簡(jiǎn)而言之,count()方法在元組中搜索給定的元素,并返回該元素在其中出現(xiàn)了多少次。
count()方法的語(yǔ)法為:
tuple.count(element)
count()方法采用一個(gè)參數(shù):
element -要查找其計(jì)數(shù)的元素
count()方法返回給定元素在元組中出現(xiàn)的次數(shù)。
# 元音元組
vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u')
# 統(tǒng)計(jì)元素 'i'
count = vowels.count('i')
# 輸出 count
print('出現(xiàn)次數(shù):', count)
# 統(tǒng)計(jì)元素 'p'
count = vowels.count('p')
# 輸出 count
print('出現(xiàn)次數(shù):', count)當(dāng)您運(yùn)行該程序時(shí),輸出將是:
出現(xiàn)次數(shù): 3 出現(xiàn)次數(shù): 0
# 隨機(jī) tuple
random = ('a', ('a', 'b'), ('a', 'b'), [3, 4])
# 統(tǒng)計(jì)元素 ('a', 'b')
count = random.count(('a', 'b'))
# 輸出 count
print("統(tǒng)計(jì) ('a', 'b') 出現(xiàn)次數(shù):", count)
# 統(tǒng)計(jì)元素 [3, 4]
count = random.count([3, 4])
# 輸出 count
print("統(tǒng)計(jì) [3, 4] 出現(xiàn)次數(shù):", count)當(dāng)您運(yùn)行該程序時(shí),輸出將是:
統(tǒng)計(jì) ('a', 'b') 出現(xiàn)次數(shù): 2
統(tǒng)計(jì) [3, 4] 出現(xiàn)次數(shù): 1