Python列表:在列表中具有重复值的heapq.nlargest索引 [英] Python lists: indices of heapq.nlargest with repeating values in list
问题描述
假设我有一个数字列表:
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
在这里,index1
和index2
均为1
.这是因为max_vals
的两个值都具有8
,而my_list.index()
只是搜索8
的第一个实例.
Here, both index1
and 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屋!