Python numpy 寻找数组中第二大和第三大的数值

2022-05-26  本文已影响0人  王叽叽的小心情

如题目所示,需要寻找数组中的第二大和第三大的数值,不能直接排序,因为直接对数组进行排序后取数值会忽略存在多个最大值的情况。因此需要对数组进行去重,有两种方法,一种是采用集合的方式去重,一种是采用np.unique()进行去重。

1. 使用集合set()去重+排序sorted()

arr = [1, 2 ,3, 3, 5, 5, 6, 7, 7]
print(sorted(set(arr))[-2])
6

2. 使用np.unique()+排序sorted()
import numpy as np

arr = [1, 2 ,3, 3, 5, 5, 6, 7, 7]
print(sorted(np.unique(arr))[-2])
6

3. 二者的效率比较

不过针对规模较大的数组,需要比较一下两者运行的效率。

使用np.unique()+排序sorted(),针对长度为10000的数组,耗时15秒

import numpy as np
from timeit import Timer

def test():
    return sorted(np.unique([i for i in range(10000)]))[-2]


if __name__ == '__main__':
    t1 = Timer("test()", "from __main__ import test")
    print(t1.timeit(10000))

# 输出结果
15.3470649

使用集合set()去重+排序sorted(),针对长度为10000的数组,耗时5秒

import timeit

print(timeit.timeit(stmt="sorted(set([i for i in range(10000)]))[-2]", number=10000))

# 输出结果
5.7564598

可见使用set()集合去重的效率更高一些。

撒花~

上一篇下一篇

猜你喜欢

热点阅读