Python list index方法:查询具有特定值的元素的索引

48 篇文章 45 订阅

目录

描述

语法和参数

返回值

使用示例

在列表中查询

在列表内的某个区间内查询

注意事项

要查询的元素在列表中不存在

要查询的元素在列表中存在多次

start大于end

start和end超出列表有效范围


描述

Python list.index方法返回某一个值的元素位于列表中的索引。

语法和参数

list.index(element, start, end)
名称含义
element要查询的元素值,不可省略的参数,可以是任意类型的对象实例
start可选整型参数,查找的起始位置。
end可选整型参数,查找的结束位置。

返回值

int。list.index方法返回参数值所在列表的索引。

使用示例

在列表中查询

index方法返回参数所在列表中的索引。

>>> demo = ["running", "pending", "error"]
>>> demo.index("running")
0

在列表内的某个区间内查询

默认情况下index方法在整个列表中搜索要查询的值。使用start和end 参数可以在列表中的某个区间搜索。当end值省略时,表示从start值对应的索引开始搜索,一直到列表的最后一个元素。当start,end值都存在时,表示从[start, end-1]闭区间内搜索。

>>> demo = ["a", "p", "p", "l", "e"]
>>> demo.index("p", 2)
2
>>> demo.index("p", 3, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'p' is not in list

注意事项

要查询的元素在列表中不存在

当要查询的元素在列表中不存在时,index方法抛出ValueError异常。

>>> demo = ["running", "pending", "error"]
>>> demo.index("finish")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'finish' is not in list

要查询的元素在列表中存在多次

当要查询的元素在列表中存在多次时,index方法返回最靠近列表头的元素的索引。

>>> demo = ["running", "pending", "error", "error"]
>>> demo.index("error")
2

因此当值在列表中存在多次时,index方法仅能返回最靠近列表头的元素的索引值,而不能将所有匹配值的索引返回。

start大于end

由于start和end可正可负,但它们在真实逻辑上表示的是列表的索引下标。当start对应的逻辑下标在end对应的逻辑下标右边或者重合时,index方法抛出ValueError异常。例如下面的代码,虽然start的值(1)大于end的值(-1),但是end值表示的逻辑索引为4,位于start的右边,因此index可以正确返回。

>>> demo = ["a", "p", "p", "l", "e"]
>>> demo.index("l", 1, -1)
3

下面的代码start值表示的逻辑索引分别在end值表示的逻辑索引的右边,重合。在这些情况下index方法抛出ValueError异常。

>>> demo = ["a", "p", "p", "l", "e"]
>>> demo.index("p", 3, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'p' is not in list
>>> demo.index("p", 1, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'p' is not in list

start和end超出列表有效范围

start和end的值涉及到以下几种可能性:

A. start和end均在列表长度有效范围中;

B. start在有效范围中,而end不在;

C. start不在有效范围中,而end在;

D. start和end均不在有效范围中。

对于场景A,我们已经论述过了,如果start和end均在长度有效范围内,index会返回被查找元素的下标,或者抛出ValueError异常。

当start和end超出列表长度有效范围后,index方法不会报错,而是将超出长度的start或end视为最大长度值,即列表最后一个元素的下标+1。

>>> demo = ["a", "p", "p", "l", "e"]
>>> demo.index("e", 0, 400)
4

在上面的代码中,end值为400,这显然超出了列表的最大范围。但是start值为0,在列表的长度范围中,因此index方法从第0个元素开始搜索元素"e",一直到最后一个元素。

对于C和D场景,index方法会抛出ValueError异常。

>>> demo = ["a", "p", "p", "l", "e"]
>>> demo.index("e", 500, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'e' is not in list
>>>
>>> demo.index("e", 400, 500)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'e' is not in list

  • 21
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值