Python 程序查找数组中的第二大元素

编写一个 Python 程序来查找 Numpy 数组中的第二大数字。我们使用 numpy sort 函数按升序对数组进行排序。接下来,我们打印倒数第二个索引位置的值。

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])
Program to Find Second Largest in an Array

此程序使用 For Loop range 查找 numpy 数组中的第二大元素。

import numpy as np

secLarr = np.array([15, 22, 75, 99, 35, 70, 120, 60])
print("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 = ", first)
print("The Second Largest Item = ", second)

使用 for 循环范围的第二大 numpy 数组项 输出

Items =  [ 15  22  75  99  35  70 120  60]
The Largest Item =  120
The Second Largest Item =  99