Python列表index()

时间:2020-02-23 14:42:54  来源:igfitidea点击:

在本教程中,我们将看到Python列表的index方法。

Python列表索引方法用于在列表中查找元素的索引

Python列表index示例

我们可以简单地使用索引方法查找列表中元素的索引。
如果有多个元素发生,那么它将返回第一个元素。
让我们在简单的例子的帮助下了解这一点。

list1=[1,2,'three','four',5]
print("Index of 'three' in list1:",list1.index('three'))

输出:

Index of 'three' in list1: 2

如果列表中不存在元素,则它将提高ValueError。

list1=[1,2,'three','four',5]
print("Index of 6 in list1:",list1.index(6))

输出:

—————————————————————————
ValueError                                Traceback (most recent call last)
 in ()
      1 list1=[1,2,'three','four',5]
      2
—-> 3 print(“Index of 6 in list1:",list1.index(6))
ValueError: 6 is not in list

如果列表中有多个元素出现,则它将返回元素的第一次出现索引。
[/datacamp_sample_code] [/datacamp_exercise]输出:

Index of 'three' in list1: 2

如果列表中不存在元素,则它将提高ValueError。

list1=[1,2,3,2,1]
print("Index of 1 in list1:",list1.index(1))
print("Index of 2 in list1:",list1.index(2))

输出:

Index of 1 in list1: 0
Index of 2 in list1: 1