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.
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.
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.
>>> seq = [100, 2, 400, 500, 400]
>>> heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])
[(3, 500), (2, 400)]
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