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列表索引查找