Python程序查找数组中的最小数

编写一个Python程序来查找数组中的最小数。numpy模块有一个内置的min()函数来返回最小值。否则,你可以使用for循环或while循环来迭代数组项,并使用if语句来查找最小项。

使用min函数查找数组中最小数的Python程序

numpy min函数返回数组中的最小或最小的值。此numpy函数返回数字和字符串数组中的最小项。为了演示相同,我们使用了int和string数组。

import numpy as np
smtarr = np.array([14, 27, 99, 10, 50, 65, 18, 4, 195, 100])
print("Numeric Numpy Array Items = ", smtarr)
print("The Smallest Number in this Numpy Array = ", min(smtarr))

strsmtarr = np.array(['UK','USA','India', 'Japan'])
print("String Numpy Array Items = ", strsmtarr)
print("The Smallest Number in this Numpy Array = ", min(strsmtarr))
Python Program to Find Smallest Number in an Array 1

使用sort()在数组中查找最小数

我们使用numpy sort函数将数组按升序排序,并打印第一个索引位置的数字,即最小数。

import numpy as np
smtarr = np.array([99, 14, 150, 11, 184, 5, 190])
print(smtarr)

print(type(smtarr))
smtarr.sort()
print(smtarr[0])
[99, 14, 150, 11, 184, 5, 190]
<class 'numpy.ndarray'>
5

使用for循环查找数组中最小数的Python程序

在这个例子中,我们将第一个值指定为最小数,for循环范围从一开始, up to smtarr length minus one。

if条件 (if(smallest > smtarr[I])) 检查是否当前numpy数组元素大于或不。如果为True,则将该值分配给Smallest变量,并将(position = i)索引值分配给position变量。

import numpy as np
smtarr = np.array([14, 27, 99, 10, 50, 65, 18, 4, 195, 100])
print(smtarr)

smallest = smtarr[0]
for i in range(1, len(smtarr)-1) :
    if(smallest > smtarr[i]) :
        smallest = smtarr[i]
        position = i
        
print("The Smallest Number   = ", smallest)
print("The Index Position = ", position)
[14, 27, 99, 10, 50, 65, 18, 4, 195, 100]
The Smallest Number   = 4
The Index Position = 7