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


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

在這篇文章中,我們將了解count() 用於元組的方法Python.這List count()一種方法元組返回給定元素在中出現的次數元組.

示例

Python3


tuple = (1, 2, 3, 1, 2, 3, 1, 2, 3)
print(tuple.count(3))

輸出:

3

Python 元組 count() 方法語法

用法: tuple.count( ele )

參數:

  • ele: 我們想要計算其出現次數的任何元素。

返回:元素在元組中出現的次數。

Python 示例中的元組 count() 方法

在Python中計算元組中元素的頻率

在這裏,我們使用 count 方法計算給定元組中特定元素的總出現次數。

Python3


# Creating tuples
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
Tuple2 = ('python', 'geek', 'python',
          'for', 'GFG', 'python', 'geeks')
# count the appearance of 3
res = Tuple1.count(3)
print('Count of 3 in Tuple1 is:', res)
# count the appearance of python
res = Tuple2.count('python')
print('Count of Python in Tuple2 is:', res)

輸出:

Count of 3 in Tuple1 is: 3
Count of Python in Tuple2 is: 3

計算元組內列表元素的數量

在這裏,我們使用 count 方法計算特定元素的總出現次數,在本例中是 list 和元組內的元組。

Python3


# Creating tuples
Tuple = (0, 1, "GFG", [3,2], 1,
         [3, 2], 'geeks', (0), ('G', 'F'))
# count the appearance of [3, 2]
res = Tuple.count([3, 2])
print('Count of [3, 2] in Tuple is:', res)

輸出:

Count of [3, 2] in Tuple is: 2

統計元組中不存在的元素

在這裏,我們使用 count 方法計算給定元組中實際不存在的特定元素的總出現次數。

Python3


# Creating tuples
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
Tuple2 = ('python', 'geek', 'python',
          'for', 'GFG', 'python', 'geeks')
# count the appearance of 3
res = Tuple1.count(5)
print('Count of 5 in Tuple1 is:', res)
# count the appearance of python
res = Tuple2.count('GeeksforGeeks')
print('Count of GeeksforGeeks in Tuple2 is:', res)

輸出:

Count of 5 in Tuple1 is: 0
Count of GeeksforGeeks in Tuple2 is: 0

計算元組中元組的出現次數

在此示例中,我們將元組嵌套在元組內,並檢查 tuple 在元組內出現的次數。

Python3


my_tuple = ((1, 2), ('a', 'b'), (1, 2), ('c', 'd'), ('a', 'b'))
count_tuple = my_tuple.count((1, 2))
print(count_tuple)  
count_xy = my_tuple.count(('x', 'y'))
print(count_xy)

輸出:

2
0


相關用法


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