📜  Python元组方法

📅  最后修改于: 2022-05-13 01:55:50.781000             🧑  作者: Mango

Python元组方法

Python元组是一个更像列表的不可变集合。 Python提供了几种处理元组的方法。在本文中,我们将借助一些示例详细讨论这两种方法。

Count() 方法

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

句法:

tuple.count(element)

其中元素是要计数的元素。

示例 1:使用 Tuple count() 方法



Python3
# Creating tuples
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
Tuple2 = ('python', 'geek', 'python', 
          'for', 'java', 'python')
  
# 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)


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


Python3
# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
  
# getting the index of 3
res = Tuple.index(3)
print('First occurrence of 3 is', res)
  
# getting the index of 3 after 4th
# index
res = Tuple.index(3, 4)
print('First occurrence of 3 after 4th index is:', res)


Python3
# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
  
# getting the index of 3
res = Tuple.index(4)


输出:

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

示例 2:将元组和列表作为元组中的元素进行计数

蟒蛇3

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

输出:

Count of (2, 3) in Tuple is: 2
Count of [3, 2] in Tuple is: 1

Index() 方法

Index() 方法从元组中返回给定元素的第一次出现。

句法:

tuple.index(element, start, end)

参数:

  • element:要搜索的元素。
  • start (可选):开始搜索的起始索引
  • end(可选):结束索引直到搜索完成

注意:如果在元组中找不到该元素,则此方法会引发 ValueError。

示例 1:使用元组 Index() 方法

蟒蛇3

# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
  
# getting the index of 3
res = Tuple.index(3)
print('First occurrence of 3 is', res)
  
# getting the index of 3 after 4th
# index
res = Tuple.index(3, 4)
print('First occurrence of 3 after 4th index is:', res)

输出:

First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5

示例 2:未找到元素时使用 Tuple() 方法

蟒蛇3

# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
  
# getting the index of 3
res = Tuple.index(4)

输出:

ValueError: tuple.index(x): x not in tuple

注意:有关Python元组的更多信息,请参阅Python元组教程。