hardikudeshi hardikudeshi - 6 months ago 58
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?

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


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


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]