Tutorial Study Image

Python count()

Python 中的 count() 函数有助于返回给定元素在元组中出现的次数。元组是一种内置数据类型,用于存储多个有序且不可更改的元素。


tuple.count(element) #where element may be a integer,string,etc.
 

count() 参数

count() 函数接受一个参数。如果缺少参数,它将返回错误。

参数 描述 必需/可选
元素 要计数的元素 必需

count() 返回值

返回值始终是一个整数,表示特定元素在元组中出现的次数。如果给定元素不在元组中,它将返回零。

输入 返回值
元素 整数(计数)

Python 中 count() 方法的示例

示例 1:元组 count() 在 Python 中如何工作?


# 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:如何计算元组中的列表和元组元素?


# 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