首页 > 编程知识 正文

Python 程序:寻找数组中第二大元素

时间:2023-11-25 09:12:54 阅读:308993 作者:GVSQ

写一个 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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。