[英]Python - Finds the index of the smallest element in the list A from index k onwards
[英]Python list index from a certain point onwards
对于列表
a = [1,2,5,3,7,2,3,1,7,4,2,3,4,2,1]
我知道如果我这样做
a.index(2)
1个
但是我想知道从某个点查找数字的最干净的方法是什么。
a.index(2,从第2点开始)
5
list.index
[doc]函数具有其他参数:
在第一个值为. index (x[, start[, end]])
x
项的列表中返回从零开始的索引。 如果没有这样的项目,则引发ValueError
。
可选参数start
和end
的解释与切片符号相同 ,用于将搜索限制到列表的特定子序列。 返回的索引是相对于完整序列的start
而不是start
参数计算的。
因此,您可以使用:
a.index(2, 2)
从索引2 (包括索引2) 开始搜索 。
通过实现list.index
,您可以传递“点”以实现所需的输出:
a= [1,2,5,3,7,2,3,1,7,4,2,3,4,2,1]
print(a.index(2, 2))
输出:
5
但是,另一种可能的解决方案是构建字典:
val = 2
a= [1,2,5,3,7,2,3,1,7,4,2,3,4,2,1]
locations = dict(enumerate([i for i, c in enumerate(a) if c == val], start=1))
print(locations.get(2, False))
输出:
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.