在python列表中找到最小值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24816669/
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
Find the minimum value in a python list
提问by ray
I want to find the minimum value in a list. I know I can use min()
, but I am learning Python and want to implement this for practice on my own:
我想在列表中找到最小值。我知道我可以使用min()
,但我正在学习 Python 并希望自己实现它以进行练习:
x=[2,3,5,9,1,0,2,3]
z=len(x)-1
i=0
for i in range(z):
if x[i]<x[i+1]:
y=x[i]
else:
y=x[i+1]
print(y)
This doesn't find the minimum though. How can I change this to find the minimum of the list x
?
但这并没有找到最小值。如何更改它以找到列表中的最小值x
?
采纳答案by msw
Try to stop indexing lists with integers. It is far easier to just iterate through the list.
尝试停止使用整数索引列表。遍历列表要容易得多。
x = [2,3,5,9,1,0,2,3]
def my_min(sequence):
"""return the minimum element of sequence"""
low = sequence[0] # need to start with some value
for i in sequence:
if i < low:
low = i
return low
print my_min(x)
回答by mrKelley
Your problem is that you are only comparing values that are right next to each other in the list. Your program should instead remember the smallest value you've checked so farand compare the others against that.
您的问题是您只比较列表中彼此相邻的值。您的程序应该记住到目前为止您检查过的最小值,并将其他值与它进行比较。
That's your hint!
这就是你的提示!
回答by bumbumpaw
add a temp (temporary variable) , this is where you will store the minimum value for x[0] and x[1]
then x[1] and x[3]
so forth. cheers
添加一个临时(临时变量),这就是你将存储的最低值,x[0] and x[1]
然后x[1] and x[3]
依此类推。干杯
回答by JishnuM
You are not keeping track of the minimum through your iteration at all. Therefore, what happens in your code in effect is that the minimum of the last two values (2 and 3, in this case) is returned.
您根本没有通过迭代跟踪最小值。因此,在您的代码中实际发生的是返回最后两个值(在本例中为 2 和 3)中的最小值。
To correct this, maintain a minimum seen so far, and update it if the value in the iteration is less than that. Then, at the end of your iteration, it will hold the minimum of the list.
要纠正此问题,请保持迄今为止看到的最小值,如果迭代中的值小于该值,则更新它。然后,在迭代结束时,它将保留列表中的最小值。
回答by Peter Sun
You're checking adjacent values and comparing them to see which one's bigger and assigning that to y. If you want to find the minimum value in your list it has to be the universal minimum as in smallest of all values. So instead of checking for the smallest element between two adjacent elements, you should check each element of the list with your current minimum value, if you come across an element that is smaller than your minimum, that element becomes your minimum.
您正在检查相邻值并比较它们以查看哪个更大并将其分配给 y。如果你想在你的列表中找到最小值,它必须是所有值中最小值的通用最小值。因此,与其检查两个相邻元素之间的最小元素,不如用当前的最小值检查列表中的每个元素,如果遇到小于最小值的元素,则该元素成为最小值。