這是我的代碼,我收到“串列索引超出范圍”的錯誤,我試圖通過考慮 for 回圈之前的第一個和最后一個值來解決這個問題,但是我不知道如何使 for 回圈排除第一個和最后一個物件,有什么想法嗎?
def minmax(List):
mins=[]
maxs=[]
if List[0]>List[1]: maxs.append(List[0])
if List[0]<List[1]: mins.append(List[0])
if List[-1]>List[-2]: maxs.append(List[-1])
if List[0]<List[1]: mins.append(List[-1])
for i in List[1:-1]:
if List[i] < List[i-1] and List[i] < List[i 1]:
mins.append(List[i])
elif List[i] > List[i-1] and i> List[i 1]:
maxs.append(List[i])
return "mins",mins,"maxs",maxs
nums=[5,0,5,0,5]
minmax(nums)
uj5u.com熱心網友回復:
您的錯誤在于您在 for 回圈中訪問元素的方式
for i in List[1:-1]:
if List[i] < List[i-1] and List[i] < List[i 1]:
mins.append(List[i])
elif List[i] > List[i-1] and i> List[i 1]:
maxs.append(List[i])
確實,ihere is an element of Listnot the index of this element,因此,List[i]也沒有任何List[i 1]意義List[i-1]。
一種修復方法是使用enumerate來跟蹤串列的當前值以及它的索引:
for n, i in enumerate(List[1:-1]):
if List[n] < List[n-1] and List[n] < List[n 1]:
mins.append(List[n])
elif List[n] > List[n-1] and i> List[n 1]:
maxs.append(List[n])
我強烈建議您使用除錯器來理解這種行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/445055.html
標籤:麻木的 循环 for循环 jupyter-笔记本
上一篇:如何使用r中的回圈生成人口
下一篇:在for回圈中更改函式的輸入變數
