Can you find the two smallest scores without a full sort?

argpartition locates a rank boundary and returns indices on each side. The partitions themselves have no guaranteed order.

numpy.argpartition in practice

Partition four latencies to retrieve the fastest two and sort just that pair for display. Define a tie rule if equal latencies straddle the cutoff.

import numpy as np
v=np.array([9,2,7,1])
np.sort(v[np.argpartition(v,1)[:2]])

Result [1, 2]

中文

只找最小的两项,是否需要全排序?

argpartition 把所选秩放在正确分区边界,两侧分区内部顺序没有保证。

numpy.argpartition 算例

对四个延迟选出最快两次,只需按秩分区,再单独排序两项以便展示。并列位于边界时要另定取舍规则。

import numpy as np
v=np.array([9,2,7,1])
np.sort(v[np.argpartition(v,1)[:2]])

结果 [1, 2]

References / 参考来源

Keep reading / 继续阅读