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]
>>> 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With