问题
I don't know how to make python "scan" through the list for a candidate and then go back to the loop again to find another candidate for the min.
candidate = 0
maximum = 0
a = [12, 10, 50, 100, 24]
for i in len(s):
for j in range(len(s)):
回答1:
You can use the builtin min function to do this
a = [12, 10, 50, 100, 24]
print min(a)
If you really want to use loop,
minimum = a[0]
for number in a:
if minimum > number:
minimum = number
print minimum
You can use max function to find the maximum in a list.
回答2:
You can write your own function to handle this for any sort of iterable, including generators:
def my_minimum(iterable):
iterable = iter(iterable)
minimum = iterable.next()
for i in iterable:
if i < minimum:
minimum = i
return minimum
>>> a = [12, 10, 50, 100, 24]
>>> my_minimum(a)
10
Which takes generators:
>>> b = xrange(20)
>>> my_minimum(b)
0
However, as the others mentioned, Python has its own built-in min
function, so I hope this question is purely academic.
>>> min(a)
10
Which also takes generators:
>>> b = xrange(20)
>>> min(b)
0
回答3:
Use the built-in min
and max
functions, like this:
>>> min([12,10,50,100,24])
10
>>> max([12,10,50,100,24])
100
来源:https://stackoverflow.com/questions/21359883/python-find-the-minimum-using-for-loops