Python列表:在列表中具有重复值的heapq.nlargest索引 [英] Python lists: indices of heapq.nlargest with repeating values in list

查看:837
本文介绍了Python列表:在列表中具有重复值的heapq.nlargest索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数字列表:

Suppose I have a list of numbers:

my_list = [3, 8, 4, 2, 8, 1, 1, 2, 5, 1]

我现在想在此列表中找到2个最大数字的索引.所以,我尝试:

I now want to find the indices of the 2 greatest numbers in this list. So, I try:

import heapq
max_vals = heapq.nlargest(2, my_list)
index1 = my_list.index(max_vals[0])
index2 = my_list.index(max_vals[1])
print index1
print index2

在这里,index1index2均为1.这是因为max_vals的两个值都具有8,而my_list.index()只是搜索8的第一个实例.

Here, both index1and index2 are 1. This is because max_vals has 8 for both values, and the my_list.index() just searches for the first instance of 8.

在这种情况下,如何获取前2个值的索引,使得index1像以前一样是1,但是index2现在是4,对应于列表中的其他8 ?

How can I get the indices of the top 2 values in this case, such that index1 is 1 as before, but index2 is now 4, corresponding to the other 8 in the list?

另一方面,在列表中找到最大值,然后再找到该值的索引似乎效率很低.有没有办法一口气做到这一点?

On a side note, it seems rather inefficient to find the maximum value in a list, and then subsequently find the index of that value. Is there not a way to achieve this in one sweep of the list?

谢谢.

推荐答案

您可以在enumerate(list)上应用heapq.nlargest"

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

这篇关于Python列表:在列表中具有重复值的heapq.nlargest索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆