hardikudeshi hardikudeshi - 4 months ago 38
Python Question

Get index of the top n values of a list in python

I have a list say

a = [5,3,1,4,10]
. I need to get a index of top two values of the list viz 5 and 10. Is there a one-liner that python offers for such a case?

Answer
sorted(range(len(a)), key=lambda i: a[i])[-2:]

or

sorted(range(len(a)), key=lambda i: a[i], reverse=True)[:2]

or

zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]

or (for long lists)

zip(*heapq.nlargest(2, enumerate(a), key=operator.itemgetter(1)))[0]