寫一個 Python 程序來尋找 Numpy 數組中的第二大數字。我們使用 numpy 排序函數對數組進行升序排序。接下來,我們在最後一個索引位置打印該值。
import numpy as np
secLarr = np.array([11, 55, 99, 22, 7, 35, 70])
print("Array Items = ", secLarr)
secLarr.sort()
print("The Second Largest Item in this Array = ", secLarr[len(secLarr) - 2])
使用 For 循環範圍查找 numpy 數組中第二大數組的 Python 程序。
import numpy as np
secLarr = np.array([15, 22, 75, 99, 35, 70, 120, 60])
print("Array Items = ", secLarr)
first = second = min(secLarr)
for i in range(len(secLarr)):
if (secLarr[i] > first):
second = first
first = secLarr[i]
elif(secLarr[i] > second and secLarr[i] < first):
second = secLarr[i]
print("The Largest Item in this Array = ", first)
print("The Second Largest Item in this Array = ", second)
使用 for 循環範圍輸出的第二大 Python numpy 數組項
Array Items = [ 15 22 75 99 35 70 120 60]
The Largest Item in this Array = 120
The Second Largest Item in this Array = 99
原創文章,作者:CFYCL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/316026.html