寫一個 Python 程序來尋找數組中的最小數。numpy min 函數返回數組中的最小值。我們使用這個 numpy min 函數返回數字和字元串數組中的最小項。
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 程序
我們使用 numpy 排序函數對數組進行升序排序,並列印第一個索引位置號,即最小。
import numpy as np
smtarr = np.array([99, 14, 150, 11, 184, 5, 190])
print("Numeric Numpy Array Items = ", smtarr)
print(type(smtarr))
smtarr.sort()
print("The Smallest Number in this Numpy Array = ", smtarr[0])
最小數值數組項目輸出
Numeric Numpy Array Items = [ 99 14 150 11 184 5 190]
<class 'numpy.ndarray'>
The Smallest Number in this Numpy Array = 5
在這個 Python 示例中,我們將第一個值指定為最小,for 循環範圍從 1 開始,遍歷到 smtarr 長度減 1。if 條件(if(minist > smtar[I])檢查當前 numpy 數組元素是否大於 minist。如果為真,則將該值(最小= smtarr[I])賦給最小變數,將(位置= i)索引值賦給位置變數。
import numpy as np
smtarr = np.array([14, 27, 99, 10, 50, 65, 18, 4, 195, 100])
print("Numeric Numpy Array Items = ", 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 in this Numpy Array = ", smallest)
print("The Index Position of the Smallest Number = ", position)
蟒陣最小物品輸出
Numeric Numpy Array Items = [ 14 27 99 10 50 65 18 4 195 100]
The Smallest Number in this Numpy Array = 4
The Index Position of the Smallest Number = 7
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/303150.html