Python:函数在没有 max() 的情况下返回列表中的最高值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19469136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Function returning highest value in list without max()?
提问by rlo5029
I need to write a function that takes a list of numbers as the parameter and returns the largest number in the list without using max()
.
我需要编写一个函数,它将数字列表作为参数并返回列表中的最大数字而不使用max()
.
I've tried:
我试过了:
def highestNumber(l):
myMax = 0
if myMax < l:
return myMax
return l
print highestNumber ([77,48,19,17,93,90])
...and a few other things that I can't remember. I just need to understand how to loop over elements in a list.
……还有一些我不记得的事情。我只需要了解如何循环列表中的元素。
采纳答案by thefourtheye
def highestNumber(l):
myMax = l[0]
for num in l:
if myMax < num:
myMax = num
return myMax
print highestNumber ([77,48,19,17,93,90])
Output
输出
93
Or You can do something like this
或者你可以做这样的事情
def highestNumber(l):
return sorted(l)[-1]
Or
或者
def highestNumber(l):
l.sort()
return l[-1]
回答by Martijn Pieters
You need to loop over all values to determine the maximum; keep track of the maximum so farand return that after completing the loop:
您需要遍历所有值以确定最大值;跟踪到目前为止的最大值并在完成循环后返回:
def highestNumber(l):
myMax = float('-inf')
for i in l:
if i > myMax:
myMax = i
return myMax
Here, float('-inf')
is a number guaranteed to be lower than any other number, making it a great starting point.
在这里,float('-inf')
是一个保证低于任何其他数字的数字,使其成为一个很好的起点。
The for
construct takes care of all the looping; you do that directly over the elements of l
, i
is assigned each element of the sequence, one by one.
该for
构造负责所有循环;你这样做正上方的元件l
,i
被分配序列的每个元素,一个接一个。
Your code forgets to loop, tests the whole list against 0
and returns the whole list if the test failed.
您的代码忘记循环,测试整个列表0
并在测试失败时返回整个列表。
回答by RAMPRASAD REDDY GOPU
function to find maximum in a list without using predefined functions
在不使用预定义函数的情况下在列表中查找最大值的函数
def max_len_list(temp):
i=1
for each in temp:
while i < max_len:
comp=each;
if comp > temp[i]:
i=i+1;
elif temp[i] > comp:
comp=temp[i];
i=i+1
return comp
list1 = [];
max_len=3;
try:
while len(list1) < max_len :
no = int(input("enter a number\n"));
list1.append(no);
except:
print "enter number not string"
max_no=max_len_list(list1);
print max_no