當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python List count()用法及代碼示例


Python List count() 是 Python 中的一個內置函數,它返回給定對象在 List 中出現的次數。 count() 函數用於對列表和字符串中的元素進行計數。

Syntax: 

list_name.count(object) 

Parameters: 

The object is the things whose count is to be returned. 



返回: 

count() method returns the count of how many times object occurs in the list.

Exception: 

If more then 1 parameter is passed in count() method, it returns a TypeError.

範例1:count()的使用

Python3


# Python3 program to count the number of times
# an object appears in a list using count() method
 
list1 = [1, 1, 1, 2, 3, 2, 1]
 
# Counts the number of times 1 appears in list1
print(list1.count(1))
 
list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']
 
# Counts the number of times 'b' appears in list2
print(list2.count('b'))
 
list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat']
 
# Counts the number of times 'Cat' appears in list3
print(list3.count('Cat'))

輸出:

4
3
2

示例 2:類型錯誤

Python3


# Python3 program to demonstrate
# the error in count() method
 
list1 = [1, 1, 1, 2, 3, 2, 1]
 
# Error when two parameters is passed.
print(list1.count(1, 2))

輸出:

Traceback (most recent call last):
  File "/home/41d2d7646b4b549b399b0dfe29e38c53.py", line 7, in 
    print(list1.count(1, 2))  
TypeError:count() takes exactly one argument (2 given)

範例3:計算列表中的元組和列表元素

Python3


# Python3 program to count the number of times
# an object appears in a list using count() method
 
list1 = [ ('Cat', 'Bat'), ('Sat', 'Cat'), ('Cat', 'Bat'),
          ('Cat', 'Bat', 'Sat'), [1, 2], [1, 2, 3], [1, 2] ]
 
# Counts the number of times 'Cat' appears in list1
print(list1.count(('Cat', 'Bat')))
 
# Count the number of times sublist
# '[1, 2]' appears in list1
print(list1.count([1, 2]))

輸出:

2
2

實際應用

假設我們要計算列表中的每個元素並將其存儲在另一個列表或字典中。

Python3


# Python3 program to count the number of times
# an object appears in a list using count() method
 
lst = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat']
 
# To get the number of occurrences
# of each item in a list
print ([ [l, lst.count(l)] for l in set(lst)])
 
# To get the number of occurrences
# of each item in a dictionary
print (dict( (l, lst.count(l) ) for l in set(lst)))

輸出:

[['Mat', 1], ['Cat', 3], ['Sat', 2], ['Bat', 1]]
{'Bat':1, 'Cat':3, 'Sat':2, 'Mat':1}





注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python List count() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。