Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lists: indices of heapq.nlargest with repeating values in list

Tags:

python

list

Suppose I have a list of numbers:

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

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

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.

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?

Thank you.

like image 339
Karnivaurus Avatar asked Feb 27 '14 17:02

Karnivaurus


1 Answers

You can apply heapq.nlargest on enumerate(list)"

>>> import heapq
>>> data = heapq.nlargest(2, enumerate(my_list), key=lambda x:x[1])
>>> indices, vals = zip(*data)
>>> indices
(1, 4)
>>> vals
(8, 8)
like image 152
Ashwini Chaudhary Avatar answered Sep 28 '22 02:09

Ashwini Chaudhary