myList=[1,2,3,5]
def findMax(aList):
biggest = aList[0]
for value in aList:
if value > biggest:
biggest = value
return biggest
此代码搜索列表中的最大数字。
我如何将其更改为while循环,而不是for循环?
答案 0 :(得分:1)
myList=[1,2,3,5]
def findMax(aList):
biggest = aList.pop()
while(len(aList) > 0):
element = aList.pop()
if (element > biggest):
biggest = element
return biggest
答案 1 :(得分:0)
您可以做的是在进入循环之前声明一个简单的计数器,然后在检查该值是否大于biggest
之后,向计数器添加一个。确保计数器是否等于阵列的大小,所以你不要超出它的范围。如果是,你就可以摆脱while循环。
答案 2 :(得分:0)
试试这个:
myList=[1,2,3,5]
def findMax(aList):
i = 0
biggest = aList[0]
while (i < len(myList)):
if myList[i] > biggest:
biggest = value
i += 1;
return biggest
答案 3 :(得分:0)
myList=[1,2,3,5]
def findMax(aList):
biggest = aList[0]
ii = 1
while ii < len(aList):
if aList[ii] > biggest:
biggest = aList[ii]
ii += 1
return biggest