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 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
.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With