hardikudeshi hardikudeshi - 1 year ago 148
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 Source
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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download