1. Python count()

发布时间:2023-12-08

Python count()

更新:2022-07-24 13:08 count()函数有助于返回元组中给定元素的出现次数。元组是一种内置的数据类型,用于存储多个元素,它是有序且不可更改的。

tuple.count(element)  # 其中 element 可以是整数、字符串等

计数()参数:

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: 如何统计 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