Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location of N max values in a python list?

Tags:

python

I have a python list(containing integers), and I want to find the indices of N highest values in a list. Where N is less than the length of the list.

I can find the N maximum values by sorting the list, but is there good way to find the location of these N maximum values?

As an example, my list is a = [10, 16, 29, 1, 4, 5, 7, 9, 13, 15], and I need to find the location of 3 highest values.

Expected result is [2, 1, 9]

like image 553
skoundin Avatar asked May 22 '18 23:05

skoundin


1 Answers

>>> import operator
>>> lst = [10,16,29,1,4,5,7,9,13,15]
>>> indexed = list(enumerate(lst)) # attach indices to the list
>>> indexed
[(0, 10), (1, 16), (2, 29), (3, 1), (4, 4), (5, 5), (6, 7), (7, 9), (8, 13), (9, 15)]
# use operator.itemgetter to get the index '1' of the (index, value) tuple
>>> top_3 = sorted(indexed, key=operator.itemgetter(1))[-3:]
>>> list(reversed([i for i, v in top_3]))
[2, 1, 9]
like image 152
Sean Breckenridge Avatar answered Oct 15 '22 20:10

Sean Breckenridge