python 中的count()
函數有助于返回列表中給定元素的出現次數。
**list.count(element)** #where element may be string, number, list, tuple, etc.
計數()參數:
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