Python 列表 count()

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

示例

# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]

# check the count of 2 count = numbers.count(2)
print('Count of 2:', count) # Output: Count of 2: 3

列表 count() 的语法

count() 方法的语法是

list.count(element)

count() 参数

count() 方法接受一个参数

  • 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

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战