Python 元组 count()

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

示例

# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'i', 'u')

# counts the number of i's in the tuple count = vowels.count('i')
print(count) # Output: 2

count() 语法

count() 方法的语法是

vowels.count('i')

这里,vowels 是元组,'i' 是要计数的元素。


count() 参数

count() 方法接受一个参数

  • 'i' - 元组中要计数的元素

count() 返回值

count() 方法返回

  • 给定元素 i 在元组中出现的次数

示例 1:Python 元组 count()

# tuple of numbers
numbers = (1, 3, 4, 1, 6 ,1 )

# counts the number of 1's in the tuple count = numbers.count(1)
print('The count of 1 is:', count)
# counts the number of 7's in the tuple count = numbers.count(7)
print('The count of 7 is:', count)

输出

The count of 1 is: 3
The count of 7 is: 0

在上面的示例中,我们使用了 count() 方法来计算元素 17 在元组中出现的次数。

这里,元组 numbers (1,3,4,1,6,1) 包含三个 1,不包含数字 7。因此,它们在元组中的计数分别为 30


示例 2:count() 用于计算元组内部的列表和元组元素

# tuple containing list and tuples
random = ('a', ('a', 'b'), ('a', 'b'), [3, 4])

# count element ('a', 'b') count = random.count(('a', 'b'))
print("The count of tuple ('a', 'b') is:", count)
# count element [3, 4] count = random.count([3, 4])
print("The count of list [3, 4] is:", count)

输出

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

在上面的示例中,我们使用了 count() 方法来计算元组 random 内部的列表和元组的数量。

元组 ('a', 'b') 出现两次,列表 [3, 4] 出现一次。因此,它们在元组中的计数分别为 21


另请阅读

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

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

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

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