我這里有問題。這是一個在自定義串列中查找最大值和最小值的程式。有些情況有效,而另一些情況則效果不佳。
#find the maximum and minimum number in an integer list
def Custom_List(MyList):
for i in range(len(MyList)):
if MyList[i] >= MyList[i-1]:
myMax = MyList[i]
if MyList[i] <= MyList[i-1]:
myMin = MyList[i]
return myMax,myMin
#inputing numbers to a list
MyList = [] #first an empty list
length = int(input("List length: )) #the length of a list
for i in range(length):
num= int(input()) #inputing our value
MyList.append(num) #and inserting them into our list
print(Custom_List(MyList))
'''Example of erroneous cases
List length: 8
1645
12
-465
325
0
134
78
664
Output: (664, 78)'''
你能告訴我這里有什么問題嗎?我將不勝感激
我希望代碼適用于每種情況,但錯誤似乎比我預期的要早出現
uj5u.com熱心網友回復:
嘗試從 1 開始回圈,這樣您就可以將串列中的第一個和第二個元素放在第一個元素處,而不是串列索引為 -1 的第一個元素
def Custom_List(MyList):
for i in range(1,len(MyList)):
if MyList[i] >= MyList[i-1]:
myMax = MyList[i]
if MyList[i] <= MyList[i-1]:
myMin = MyList[i]
return myMax,myMin
uj5u.com熱心網友回復:
我們可以在不使用任何索引的情況下完成這項任務。我們使用 2 個變數,它們最終將保存最小值/最大值,并且它們使用串列 [0] 中的一個元素進行預設。我們運行一個for回圈并將回圈變數與最小值/最大值的當前值進行比較。
def Custom_List(MyList):
# preset min, max with a value from the list
myMax = MyList[0]
myMin = MyList[0]
for num in MyList:
if num > myMax:
myMax = num
if num < myMin:
myMin = num
return myMax,myMin
MyList = [1645, 12, -465, 325, 0, 134, 78, 664]
print(Custom_List(MyList))
結果:(1645, -465)
uj5u.com熱心網友回復:
您忘記用引號結束字串:
length = int(input("List length: )) #the length of a list
嘗試這個:
#find the maximum and minimum number in an integer list
def Custom_List(MyList):
for i in range(len(MyList)):
if MyList[i] >= MyList[i-1]:
myMax = MyList[i]
if MyList[i] <= MyList[i-1]:
myMin = MyList[i]
return myMax,myMin
#inputing numbers to a list
MyList = [] #first an empty list
length = int(input("List length: ")) #the length of a list
for i in range(length):
num= int(input()) #inputing our value
MyList.append(num) #and inserting them into our list
print(Custom_List(MyList))
'''Example of erroneous cases
List length: 8
1645
12
-465
325
0
134
78
664
Output: (664, 78)'''
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527081.html
上一篇:如何使用串列推導使嵌套串列的長度等于串列中數字的值?
下一篇:Python中的正則運算式匹配
