Python 中的 count() 函数有助于返回给定元素在列表中出现的次数。
list.count(element) #where element may be string, number, list, tuple, etc.
count() 函数接受一个参数。如果向此方法传递多个参数,它将返回 TypeError。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 元素 | 要计数的元素 | 必需 |
返回值应为整数,表示给定元素的计数。如果列表中未找到给定元素,则返回 0。
| 输入 | 返回值 |
|---|---|
| 任何元素 | 整数(计数) |
# 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
# 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