我的函式在第一次滿足條件時不會停止(串列中的最小值在 start_index 開始時開始)。我必須添加什么才能實作它。我的代碼是:
def index_min(l, start_index):
min_ele = l[start_index]
idx = []
for i in range(start_index, len(l)):
if l[i] <= min_ele:
min_ele = l[i]
idx = i
return idx
print(index_of_min([10, 7, 19, 16, 5, 10, 5, 1, 5, 4, 6, 2, 3, 7, 12, 8, 9, 18, 1, 10, 7, 18],6))
它回傳索引 18 而不是索引 7 開始索引是 6。
uj5u.com熱心網友回復:
我假設你打算index_min()在print()宣告中呼叫。
如果您希望獲得最小數字的第一次出現,您可以將 the 更改<=為 a <:
def index_min(l, start_index):
min_ele = l[start_index]
idx = []
for i in range(start_index, len(l)):
# If we see a value equal to the minimum seen so far, don't update the index.
if l[i] < min_ele:
min_ele = l[i]
idx = i
return idx
print(index_min([10, 7, 19, 16, 5, 10, 5, 1, 5, 4, 6, 2, 3, 7, 12, 8, 9, 18, 1, 10, 7, 18],6))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/397238.html
上一篇:如何在不回圈的情況下更新Pandas資料框的所有單元格值?
下一篇:猜謎游戲不會停止
