Home > database >  finding the indices of the most maximum values in a list effectively
finding the indices of the most maximum values in a list effectively

Time:09-01

Suppose we have a list: [1, 3.5, -1, 7, 10, 20, 5, 17, 31, -5]

I want to write a function that returns the indices of the first 3 maximum values in order.

For example in this case the results would be: [8, 5, 7]

I know one way is to write nested-loops, however, can there be any other effective way to achieve this?

CodePudding user response:

Use heapq.nlargest to find the n largest values.

from heapq import nlargest
from operator import itemgetter

l = [1, 3.5, -1, 7, 10, 20, 5, 17, 31, -5]

indices_of_3_largest = [i for i,_ in nlargest(3, enumerate(l), itemgetter(1))]

print(indices_of_3_largest)
# [8, 5, 7]

CodePudding user response:

zip the list with the indices, sort it, and take the first 3 values

lst = [1, 3.5, -1, 7, 10, 20, 5, 17, 31, -5]
indices = [i for _, i in sorted(zip(lst, range(len(lst))), reverse=True)[:3]]
print(indices) # [8, 5, 7]

CodePudding user response:

This can generate the result in one step, but the less elegant dunder method is used as the key:

>>> lst = [1, 3.5, -1, 7, 10, 20, 5, 17, 31, -5]
>>> heapq.nlargest(3, range(len(lst)), lst.__getitem__)
[8, 5, 7]

CodePudding user response:

lambda function do this things easier.

Code:

def sort_index(lst, rev=True):
    index = range(len(lst))
    s = sorted(index, reverse=rev, key=lambda i: lst[i])
    return s
score = [1, 3.5, -1, 7, 10, 20, 5, 17, 31, -5]
sort_index(score)[:3]

Result:

[8, 5, 7]

CodePudding user response:

You could use np.argsort:

import numpy as np
ar = [1, 3.5, -1, 7, 10, 20, 5, 17, 31, -5]
ar_argsort = np.argsort(ar)
reversed_argsort = ar_argsort[::-1]
indices_3_max = reversed_argsort[0:3]
print(indices_3_max)

Result:

[8 5 7]

Concise version of above in one line:

ar_argsort = np.argsort(ar)[::-1][0:3]
  • Related