编写一个 Python 程序来查找数组中的最小值和最大值。numpy 模块具有最小值和最大值功能,用于返回 numpy 数组中的最小值和最大值。我们使用这些 numpy min 和 max 函数来返回数字和字符串数组中的最小值和最大值。
# Smallest and Largest Array Item
import numpy as np
smtlgtarr = np.array([14, 120, 50, 11, 65, 99, 920,8, 195, 120])
print("Numeric Numpy Array Items = ", smtlgtarr)
print("The Smallest Number in this Numpy Array = ", min(smtlgtarr))
print("The Largest Number in this Numpy Array = ", max(smtlgtarr))
strsmtlgtarr = np.array(['UK', 'Brazil', 'USA','India', 'Japan'])
print("String Numpy Array Items = ", strsmtlgtarr)
print("The Smallest Number in this Numpy Array = ", min(strsmtlgtarr))
print("The Largest Number in this Numpy Array = ", max(strsmtlgtarr))
寻找数组中的最小值和最大值的 Python 程序
我们使用 numpy 排序函数对 numpy 数组进行升序排序。接下来,我们在第一个和最后一个索引位置打印数字,这是最小和最大数组值。
# Largest and Smallest Array Item
import numpy as np
smtlgtarr = np.array([99, 120, 50, 9, 428, 16, 190])
print("Numpy Array Items = ", smtlgtarr)
smtlgtarr.sort()
lgtlength = len(smtlgtarr) - 1
print("The Smallest Number in smtlgtarr Numpy Array = ", smtlgtarr[0])
print("The Largest Number in smtlgtarr Numpy Array = ", smtlgtarr[lgtlength])
Python Numpy 数组最小值和最大值输出
Numpy Array Items = [ 99 120 50 9 428 16 190]
The Smallest Number in smtlgtarr Numpy Array = 9
The Largest Number in smtlgtarr Numpy Array = 428
在这个 Python 示例中,我们将第一个值分配给最小和最大的变量。if 条件(if(最大的< smtlgtarr[I])检查当前 numpy 数组项是否小于最大值。如果为真,则将该值赋给最大的变量(最大= smtlgtarr[I]),将索引值赋给 larposition (larposition = i)变量。下一个 if 条件(if(最小> smtlgtarr[I])检查项目小于最小。如果为真,(minist = smtlgtarr[I])更改最小值并分配该(smtposition = i)索引位置。
# Smallest Array Item
import numpy as np
smtlgtarr = np.array([99, 120, 625, 150, 9, 428, 716, 190])
print("Numpy Array Items = ", smtlgtarr)
smallest = smtlgtarr[0]
largest = smtlgtarr[0]
for i in range(1, len(smtlgtarr) - 1) :
if(largest < smtlgtarr[i]) :
largest = smtlgtarr[i]
larposition = i
if(smallest > smtlgtarr[i]) :
smallest = smtlgtarr[i]
smtposition = i
print("The Smallest Number in this Numpy Array = ", smallest)
print("The Index Position of the Smallest Number = ", smtposition)
print("The Largest Number in this Numpy Array = ", largest)
print("The Index Position of the Largest Number = ", larposition)
Python Numpy 数组最大值和最小值输出
Numpy Array Items = [ 99 120 625 150 9 428 716 190]
The Smallest Number in this Numpy Array = 9
The Index Position of the Smallest Number = 4
The Largest Number in this Numpy Array = 716
The Index Position of the Largest Number = 6