python 示例
列表count()方法 (List count() Method)
count() method is used to count the total number of the specified element, the method is called with this list (original list) and an element is passed as an argument and it returns the frequency of the given element.
count()方法用于对指定元素的总数进行计数,使用此列表(原始列表)调用该方法,并将一个元素作为参数传递,并返回给定元素的频率。
Syntax:
句法:
list_name.count(element)
Parameter(s):
参数:
element – It represents an element whose frequency to be counted.
element –代表要计数其频率的元素。
Return value:
返回值:
The return type of this method is <class 'int'>, it returns an integer (zero or greater than 0) value that is the frequency of the given element.
此方法的返回类型为<class'int'> ,它返回一个整数(零或大于0)值,该值是给定元素的频率。
Example 1:
范例1:
# Python List count() Method with Example
# declaring the list
cars = ["Porsche", "Audi", "Lexus", "Porsche", "Audi"]
# printing the list
print("cars: ", cars)
# counting the frequency of "Porsche"
cnt = cars.count("Porsche")
print("Porsche's frequency is:", cnt)
# counting the frequency of "Lexus"
cnt = cars.count("Lexus")
print("Lexus's frequency is:", cnt)
# counting the frequency of "BMW"
cnt = cars.count("BMW")
print("BMW's frequency is:", cnt)
Output
输出量
cars: ['Porsche', 'Audi', 'Lexus', 'Porsche', 'Audi']
Porsche's frequency is: 2
Lexus's frequency is: 1
BMW's frequency is: 0
Example 2:
范例2:
# Python List count() Method with Example
# declaring the lists
x = ["ABC", "XYZ", "PQR","ABC", "XYZ", "PQR"]
y = ["PQR", "MNO", "YXZ", "YXZ"]
z = ["123", "456", "789"]
# printing the frequency of given element
print('x.count("ABC"):', x.count("ABC"))
print('y.count("YXZ"):', y.count("YXZ"))
print('z.count("789"):', z.count("789"))
Output
输出量
x.count("ABC"): 2
y.count("YXZ"): 2
z.count("789"): 1
翻译自: https://www.includehelp.com/python/list-count-method-with-example.aspx
python 示例