📅  最后修改于: 2020-09-20 13:35:21             🧑  作者: Mango
列表index()
方法的语法为:
list.index(element, start, end)
列表index()
方法最多可以使用三个参数:
index()
方法返回列表中给定元素的索引。 ValueError
异常。 注意: index()
方法仅返回匹配元素的第一个匹配项。
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
输出
The index of e: 1
The index of i: 2
# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']
# index of'p' is vowels
index = vowels.index('p')
print('The index of p:', index)
输出
ValueError: 'p' is not in list
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 2
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
输出
The index of e: 1
The index of i: 6
Traceback (most recent call last):
File "*lt;string>", line 13, in
ValueError: 'i' is not in list