Python 取出数组中最大/小的 n 个(重复)元素以及索引

首先参考:

  1. Python获取列表中最大/最小的n个元素及索引
  2. Python获取list中最大或最小的n个数及其索引

但都不是很优雅,尤其是在有重复元素的情况下

于是有了:Python lists: indices of heapq.nlargest with repeating values in list

1
2
3
4
5
6
7
8
>>> import heapq
>>> my_list = [3, 8, 4, 2, 8, 1, 1, 2, 5, 1]
>>> data = heapq.nlargest(2, enumerate(my_list), key=lambda x:x[1])
>>> indices, vals = zip(*data)
>>> indices
(1, 4)
>>> vals
(8, 8)

Python 取出数组中最大/小的 n 个(重复)元素以及索引
https://wonderhoi.com/2024/10/10/Python-取出数组中最大-小的-n-个-重复-元素以及索引/
作者
wonderhoi
发布于
2024年10月10日
许可协议