Tutorial Study Image

Python index()

Python 中的 index() 函数有助于返回给定元素在元组中的索引。我们还可以通过元组提供搜索的起始和结束点。


tuple.index(element, start, end)  #where the element may be string, number, list, etc
 

index() 参数

index() 方法接受三个参数。此方法的输出应为一个整数值,指示元素的 position。

参数 描述 必需/可选
元素 要搜索的元素 必需
开始 (start) 从此索引开始搜索 可选
结束 (end) 在此索引之前搜索元素 可选

index() 返回值

如果该方法找到给定元素的多个匹配项,它将仅返回第一次出现的索引。

输入 返回值
元素   元素的索引  
如果没有元素 ValueError 异常

Python 中 index() 方法的示例

示例 1:如何查找元组中元素的索引?


# alphabet tuple
alphabet = ('a', 'b', 'c', 'e', 'd', 'e', 'f')

# index of 'c' in alphabet
indexpos = alphabet.index('c')
print('The index of c:', indexpos)

# element 'e' is searched
# index of the first 'e' is returned
indexpos = alphabet.index('e')

print('The index of e:', indexpos)
 

输出


The index of c: 2
The index of e: 3

示例 2:如何查找缺失元素的索引?


# alphabet tuple
alphabet = ('a', 'b', 'c', 'd', 'e', 'f')


# index of 'g' in alphabet
indexpos = alphabet.index('g')
print('The index of g:', indexpos)
 

输出


ValueError: alphabet.index('g'): g not in tuple