📅  最后修改于: 2020-07-14 04:37:09             🧑  作者: Mango
index()是Python中的内置函数,它从列表的开头搜索给定元素,并返回该元素出现的最低索引。
句法 :
list_name.index(element, start, end)
参数:
element-将返回其最低索引的元素。
start(可选)-搜索开始的位置。
end(可选)-搜索结束的位置。
返回值:
返回元素出现的最低索引。
错误:
如果搜索到任何不存在的元素,
则返回ValueError
代码1:
# 用于列表index()方法演示的Python3程序
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# 将在列表1中打印索引“ 4"
print(list1.index(4))
list2 = ['cat', 'bat', 'mat', 'cat', 'pet']
# 将在list2中打印'cat'的索引
print(list2.index('cat'))
输出:
3
0
代码2:
# 演示index()方法的Python3程序
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# 将在索引为4到8的子列表中打印索引“4"。
print(list1.index(4, 4, 8))
# 将在索引为1到7的子列表中打印索引“1"。
print(list1.index(1, 1, 7))
list2 = ['cat', 'bat', 'mat', 'cat',
'get', 'cat', 'sat', 'pet']
# 将在索引为2到6的子列表中打印'cat'的索引
print(list2.index('cat', 2, 6 ))
输出:
7
4
3
代码3:
# 用于列表index()方法演示的Python3程序
# 具有子列表和元组的随机列表
list1 = [1, 2, 3, [9, 8, 7], ('cat', 'bat')]
# 将打印子列表的索引[9,8,7]
print(list1.index([9, 8, 7]))
# 将在列表中打印元组的索引(“ cat",“ bat")
print(list1.index(('cat', 'bat')))
输出:
3
4
代码#4: ValueError
# 演示index()方法错误的Python3程序
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# 返回ValueError
print(list1.index(10))
输出:
Traceback (most recent call last):
File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in
print(list1.index(10))
ValueError: 10 is not in list