N个最大值在python列表中的位置?

Skoundin

我有一个python列表(包含整数),我想在列表中找到N个最大值的索引。其中N小于列表的长度。

我可以通过对列表进行排序来找到N个最大值,但是有什么好的方法来找到这N个最大值的位置?

例如,我的列表是a = [10、16、29、1、4、5、7、9、13、15],并且我需要找到3个最高值的位置。

预期结果是[2,1,9]

肖恩·布雷肯里奇
>>> import operator
>>> lst = [10,16,29,1,4,5,7,9,13,15]
>>> indexed = list(enumerate(lst)) # attach indices to the list
>>> indexed
[(0, 10), (1, 16), (2, 29), (3, 1), (4, 4), (5, 5), (6, 7), (7, 9), (8, 13), (9, 15)]
# use operator.itemgetter to get the index '1' of the (index, value) tuple
>>> top_3 = sorted(indexed, key=operator.itemgetter(1))[-3:]
>>> list(reversed([i for i, v in top_3]))
[2, 1, 9]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章