Tutorial Study Image

Python index()

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


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

index() 参数

此方法接受三个参数。此方法的输出应为一个整数值,表示元素的位置。

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

index() 返回值

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

输入 返回值
元素 元素的索引
如果不存在元素 ValueError 异常

Python 中 index() 方法的示例

示例 1:index() 在 Python 中如何工作


# alphabet list
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:如果搜索的元素不在列表中,index() 的行为


# alphabet list
alphabet = ['a', 'b', 'c', 'd', 'e', 'f']


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

输出


ValueError: 'g' is not in list

示例 3:通过给定起始和结束参数来使用 index()


# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'd']

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

# 'd' after the 4th index is searched
indexpos = alphabets.index('i', 4)   # 7
print('The index of d:', indexpos)

# 'd' between 4rd and 6th index is searched
indexpos = alphabets.index('d', 4, 6)   # Error!
print('The index of d:', indexpos)
 

输出


The index of c: 2
The index of d: 7
Traceback (most recent call last):
  File "*lt;string>", line 13, in 
ValueError: 'd' is not in list