Python 在浮点数组中找到最小值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3499026/
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 a minimum value in an array of floats
提问by pjehyun
how would one go about finding the minimum value in an array of 100 floats in python?
I have tried minindex=darr.argmin()and print darr[minindex]with import numpy(darr is the name of the array)
如何在 python 中的 100 个浮点数组中找到最小值?我已经尝试minindex=darr.argmin()和print darr[minindex]与import numpy(darr是阵列的名称)
but i get:
minindex=darr.argmin()
但我得到:
minindex=darr.argmin()
AttributeError: 'list' object has no attribute 'argmin'
AttributeError: 'list' object has no attribute 'argmin'
what might be the problem? is there a better alternative?
可能是什么问题?有更好的选择吗?
thanks in advance
提前致谢
采纳答案by Greg Hewgill
Python has a min()built-in function:
Python 有一个min()内置函数:
>>> darr = [1, 3.14159, 1e100, -2.71828]
>>> min(darr)
-2.71828
回答by unutbu
If you want to use numpy, you must define darrto be a numpy array, not a list:
如果要使用 numpy,则必须定义darr为 numpy 数组,而不是list:
import numpy as np
darr = np.array([1, 3.14159, 1e100, -2.71828])
print(darr.min())
darr.argmin()will give you the index corresponding to the minimum.
darr.argmin()会给你对应于最小值的索引。
The reason you were getting an error is because argminis a method understood by numpy arrays, but not by Python lists.
您收到错误的原因是因为argmin是 numpy 数组理解的方法,但 Python 不理解lists。
回答by Pedro Machado
You need to iterate the 2d array in order to get the min value of each row, then you have to push any gotten min value to another array and finally you need to get the min value of the array where each min row value was pushed
您需要迭代二维数组以获得每一行的最小值,然后您必须将任何获得的最小值推送到另一个数组,最后您需要获取推送每个最小行值的数组的最小值
def get_min_value(self, table):
min_values = []
for i in range(0, len(table)):
min_value = min(table[i])
min_values.append(min_value)
return min(min_values)

