6. Python count()

发布时间:2023-12-08

Python count()

更新:2022-07-24 13:02 count() 函数有助于返回列表中给定元素的出现次数。

list.count(element)  # where element may be string, number, list, tuple, etc. 

count() 参数:

count() 函数接受一个参数。如果向该方法传递了多个参数,它将返回一个类型错误。

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

count() 返回值

返回值应该是显示给定元素计数的整数。如果在列表中找不到给定的元素,则返回 0。

投入 返回值
任何元素 整数(计数)

Python 中 count() 方法的示例

示例 count() 在 Python 中是如何工作的

# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'c']
# count element 'c'
count = alphabets.count('c')
# print count
print('The count of c is:', count)
# count element 'f'
count = alphabets.count('f')
# print count
print('The count of f is:', count) 

输出:

The count of c is: 2
The count of f is: 0

示例 2: 如何计数列表中的元组和列表元素

# random list
randomlist = ['a', ('a', 'b'), ('a', 'b'), [1, 2]]
# count element ('a', 'b')
countof = randomlist.count(('a', 'b'))
# print count
print("The count of ('a', 'b') is:", countof)
# count element [1, 2]
countof = randomlist.count([1, 2])
# print count
print("The count of [1, 2] is:", countof) 

输出:

The count of ('a', 'b') is: 2
The count of [1, 2] is: 1