[英]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.