摘要:在本节中,你将学习如何在列表中查找元素的索引。
index()函数查找元素索引
要在列表中查找元素的索引,可以使用 index()
函数。
以下示例定义了一个城市列表,并使用 index()
方法获取值为 'Mumbai' 的元素的索引:
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']
result = cities.index('Mumbai')
print(result)
输出:
3
它会按预期返回 3。
然而,如果你尝试使用 index()
函数查找列表中不存在的元素,将会引发错误。
以下示例使用 index()
函数在 cities
列表中查找大阪(Osaka
)城市:
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']
result = cities.index('Osaka')
print(result)
错误:
ValueError: 'Osaka' is not in list
要修复这个问题,你需要使用 in
运算符。
使用 in
运算符判断元素存在性
如果某个值在列表中则in
运算符返回 True
,否则返回 False
。
在使用 index()
函数之前,你可以使用 in
运算符来检查你想要查找的元素是否在列表中。例如:
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']
city = 'Osaka'
if city in cities:
result = cities.index(city)
print(f"The {city} has an index of {result}.")
else:
print(f"{city} doesn't exist in the list.")
输出:
Osaka doesn't exist in the list.
总结
使用
in
运算符与index()
函数来查找元素是否在列表中。