Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

heapq.nlargest index of returned result in original sequence

How do I return the index in the original list of the nth largest items of an iterable

heapq.nlargest(2, [100, 2, 400, 500, 400])

output = [(3,500), (2, 400)]

This already cost me a couple hours. I can't figure it out.

like image 221
Joey Avatar asked Jun 29 '10 10:06

Joey


People also ask

What does Heapq Nlargest return?

The nlargest() function of the Python module heapq returns the specified number of largest elements from a Python iterable like a list, tuple and others. The function nlargest() can also be passed a key function that returns a comparison key to be used in the sorting.

How does Heapq Nsmallest work?

nsmallest uses one of two algorithms. If the number of items to be returned is more than 10% of the total number of items in the heap, then it makes a copy of the list, sorts it, and returns the first k items.


1 Answers

>>> seq = [100, 2, 400, 500, 400]
>>> heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])
[(3, 500), (2, 400)]
like image 101
SilentGhost Avatar answered Sep 29 '22 13:09

SilentGhost