共計 391 個字符,預計需要花費 1 分鐘才能閱讀完成。
Python 中 count 函數是用于統計某個元素在列表、字符串或元組中出現的次數的方法。其語法格式為:count(element),其中 element 表示要統計的元素。
示例:
- 統計列表中某個元素出現的次數:
numbers = [1, 2, 3, 3, 4, 3]
count = numbers.count(3)
print(count) # 輸出:3
- 統計字符串中某個字符出現的次數:
text = "Hello, World!"
count = text.count('o')
print(count) # 輸出:2
- 統計元組中某個元素出現的次數:
data = (1, 2, 3, 4, 4, 4)
count = data.count(4)
print(count) # 輸出:3
需要注意的是,count 方法只能用于可迭代對象(如列表、字符串、元組),對于字典等不支持迭代的類型無法使用 count 方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完