Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get indices of the top N values of a list

Tags:

python

list

I have a list say a = [5,3,1,4,10]. I need to get indices of the top two values of the list, that is for 5 and 10 I would get [0, 4]. Is there a one-liner that Python offers for such a case?

like image 202
hardikudeshi Avatar asked Oct 25 '12 14:10

hardikudeshi


People also ask

How do you get the indices of top n values in NumPy array?

In order to get the indices of N maximum values in a NumPy array, we can use the argsort() function.

How do you find the index of an element in a list of lists?

By using the list. index() method, we can easily get the element index value from list. In this example we have define a list of integer values and uses the list. index() method we can get the index of the item whose value is '210'.

How do you print the top 5 elements of a list in Python?

Method #1 : Using sorted() + lambda The combination of above functionality can be used to perform this particular task. In this, we just employ sorted function with reverse flag true, and print the top N elements using list slicing.

How do you find the top 3 values in Python?

If you want to get the indices of the three largest values, you can just slice the list. It also supports sorting from smallest to largest by using the parameter rev=False .


2 Answers

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

or

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

or

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

or (for long lists), consider using heapq.nlargest

zip(*heapq.nlargest(2, enumerate(a), key=operator.itemgetter(1)))[0] 
like image 68
Fred Foo Avatar answered Sep 22 '22 05:09

Fred Foo


Just a NumPy alternative:

import numpy as np  top_2_idx = np.argsort(a)[-2:] top_2_values = [a[i] for i in top_2_idx] 
like image 21
aikramer2 Avatar answered Sep 23 '22 05:09

aikramer2