Python List index() 方法用于检索出现指定对象的列表中的最低索引。对象可以是任何东西;另一个列表、元组、集合等形式的单个元素或元素集合。
该方法还接受两个可选参数来限制列表中的搜索范围。这两个参数定义搜索的开始和结束位置;基本上就像 Python 中的 slice notation 一样工作。在这种情况下,返回的最低索引将相对于起始索引,而不是列表的第 0 个索引。
语法
以下是 Python List index() 方法的语法 -
list.index(obj[, start[, end]])
参数
obj − 这是要找出的对象。
- start − (可选) 搜索开始的起始索引。
- end − (可选) 搜索结束的结束索引。
返回值
此方法返回列表中找到对象的第一个索引。如果在列表中找不到该对象,则会引发 ValueError 。
例以下示例显示了 Python List index() 方法的用法。
aList = [123, 'xyz', 'zara', 'abc'];
print("Index for xyz : ", aList.index( 'xyz' ))
print("Index for zara : ", aList.index( 'zara' ))
当我们运行上述程序时,它会产生以下结果——
Index for xyz : 1
Index for zara : 2
Index for zara : 2
例
现在,如果我们还将一些值作为可选参数 start 和 end 传递,该方法将限制在这些索引内的搜索。
listdemo = [123, 'a', 'b', 'c', 'd', 'e', 'a', 'g', 'h']
ind = listdemo.index('a', 3, 7)
print("Lowest index at which 'a' is found is: ", ind)
如果我们编译并运行上面的程序,输出实现如下 -
Lowest index at which 'a' is found is: 6
例
但是,这可能会引发一个问题,即如果某个值存在于列表中,但不在搜索范围内,则返回值将是多少?让我们看看下面这个场景的示例。
listdemo = ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i']
# The value 'a' is not present within the search range of the list
ind = listdemo.index('a', 2, 5)
# Print the result
print("Lowest index at which 'a' is found is: ", ind)
执行上面的程序将引发 ValueError,因为该值不存在于给定的搜索范围内。
Traceback (most recent call last):
File "main.py", line 4, in
ind = listdemo.index('a', 2, 5)
ValueError: 'a' is not in list
File "main.py", line 4, in
ind = listdemo.index('a', 2, 5)
ValueError: 'a' is not in list
例
当 value 在列表中不存在时,通常也会引发 ValueError 。这不需要传递可选参数。
listdemo = ['b', 'c', 'd', 'e', 'g', 'h', 'i']
# The value 'a' is not present within the list
ind = listdemo.index('a')
# Print the result
print("Lowest index at which 'a' is found is: ", ind)
在编译上面的程序时,输出如下 -
Traceback (most recent call last):
File "main.py", line 4, in
ind = listdemo.index('a')
ValueError: 'a' is not in list
File "main.py", line 4, in
ind = listdemo.index('a')
ValueError: 'a' is not in list