python列表索引查找_在Python中给定包含该项目的列表的情况下查找项目的索引

python列表索引查找

Python provides an inbuilt function called index(), which iterates through a list for an element within the start and end range of the list and returns the index of the specified element.

Python提供了一个称为index()的内置函数,该函数遍历列表的开头和结尾范围内的元素的列表,并返回指定元素的索引

Syntax:

句法:

    list.index(x[, start[, end]])

The index() returns zero-based index in the list of the first item whose value is equal to x and raises a ValueError if there is no such item.

index()在值等于x的第一项列表中返回从零开始的索引,如果没有该项,则引发ValueError

Arguments:

参数:

  • x = item whose lowest index will be returned

    x =将返回其最低索引的项目

  • start and end (optional) = used to limit the search to a particular subsequence of the list

    开始和结束 (可选)=用于将搜索限制到列表的特定子序列

Example Implementation

示例实施

Scenario 1: retrieve index without providing optional arguments

方案1:在不提供可选参数的情况下检索索引

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_list = ['bangalore','chennai','mangalore','vizag','delhi']
>>> print(test_list.index('bangalore'))
0
>>> test_list_1 = [1,2,3,4,5]
>>> print(test_list_1.index(4))
3

Scenario 2: retrieve index, providing the start and end limit

方案2:检索索引,提供开始和结束限制

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_list = ['bangalore','chennai','mangalore','vizag','delhi']
#finds the item 'bangalore' only within 0th to 3rd element in list and returns the index
>>> print(test_list.index('bangalore',0,3))
0


#finds the item 'bangalore' only within 1st to 3rd element in list and returns the index, and since the item 'bangalore' is not in that range, we get the exception
>>> print(test_list.index('bangalore',1,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'bangalore' is not in list
>>>

Scenario 3: Demonstrating the ValueError

方案3:演示ValueError

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_list = ['bangalore','chennai','mangalore','vizag','delhi']
>>> print(test_list.index('bhopal'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'bhopal' is not in list
>>>


翻译自: https://www.includehelp.com/python/find-the-index-of-an-item-given-a-list-containing-it.aspx

python列表索引查找

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值