编写一个 Python 程序来查找元组中给定项的索引。它有一个内置函数,该函数返回给定元组项的索引。此函数返回第一个找到值的索引位置,其语法是
TupleName.index(tupleValue, start, end)
如果指定了起始值,则函数将从该位置开始查找。同样,如果我们设置了结束位置,元组索引函数将在该数字处停止查找。第三个示例从第四个位置开始查找,下一个示例将从第七个位置开始查找。
numtup = (11, 33, 55, 77, 99, 111, 77, 121, 13, 55, 77)
print(numtup)
index1 = numtup.index(33)
print("Index Position of 33 = ", index1)
index2 = numtup.index(77)
print("Index Position of 77 = ", index2)
index3 = numtup.index(77, 4)
print("Index Position of 77 = ", index3)
index4 = numtup.index(77, 7)
print("Index Position of 77 = ", index4)

Python 程序查找元组项的索引示例
第三个示例中的代码从第八个位置开始查找“a”,并在第十三位置停止。
strTup = tuple("tutorialgateway")
print(strTup)
index1 = strTup.index("a")
print("Index Position of a = ", index1)
index2 = strTup.index("t", 3)
print("Index Position of t = ", index2)
index3 = strTup.index("a", 8, 13)
print("Index Position of a = ", index3)
index4 = strTup.index("x")
print("Index Position of x = ", index4)
('t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'g', 'a', 't', 'e', 'w', 'a', 'y')
Index Position of a = 6
Index Position of t = 10
Index Position of a = 9
Traceback (most recent call last):
File "/Users/suresh/Desktop/simple.py", line 13, in <module>
index4 = strTup.index("x")
ValueError: tuple.index(x): x not in tuple
不使用函数查找元组项索引的程序
在此示例中,我们使用 for 循环和 enumerate 来迭代元组值。所有示例中的 if 语句将检查元组中给定值的索引位置。第一个示例中的 break 语句将退出循环并打印第一个找到项的位置。第二个和第三个将打印 元组项的所有索引位置。
numtup = (10, 20, 30, 20, 40, 50, 20, 70, 80, 20)
print(numtup)
val = 20
for i in range(len(numtup)):
if numtup[i] == val:
print("Index Position of 20 = ", i)
break
print("All the Index Positions")
for i in range(len(numtup)):
if numtup[i] == val:
print("Index Position of 20 = ", i)
print("All the Index Positions using enumerate")
for i, x in enumerate(numtup):
if x == val:
print("Index Position of 20 = ", i)
输出
(10, 20, 30, 20, 40, 50, 20, 70, 80, 20)
Index Position of 20 = 1
All the Index Positions
Index Position of 20 = 1
Index Position of 20 = 3
Index Position of 20 = 6
Index Position of 20 = 9
All the Index Positions using enumerate
Index Position of 20 = 1
Index Position of 20 = 3
Index Position of 20 = 6
Index Position of 20 = 9