📜  Python list count()

📅  最后修改于: 2020-09-20 13:36:05             🧑  作者: Mango

count()方法返回指定元素出现在列表中的次数。

count()方法的语法为:

list.count(element)

count()参数

count()方法采用一个参数:

  1. element-要计算的元素

从count()返回值

count()方法返回element出现在列表中的次数。

示例1:count()的使用

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i'
count = vowels.count('i')

# print count
print('The count of i is:', count)

# count element 'p'
count = vowels.count('p')

# print count
print('The count of p is:', count)

输出

The count of i is: 2
The count of p is: 0

示例2:计算列表中的元组和列表元素

# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]

# count element ('a', 'b')
count = random.count(('a', 'b'))

# print count
print("The count of ('a', 'b') is:", count)

# count element [3, 4]
count = random.count([3, 4])

# print count
print("The count of [3, 4] is:", count)

输出

The count of ('a', 'b') is: 2
The count of [3, 4] is: 1