0

I have a list a = [1, 5, 2, 8]

I need a function that will return the indexes of the entries sorted by their values, i.e. b = [3, 1, 2, 0]

I came up with a function to do this:

def indices_sorted_by_val(a, reverse=True):
    return [ y[0] for y in  sorted( [(i,a[i]) for i in range(len(a))], key=lambda x: x[1], reverse=reverse )]

But it's messy and hard to read. Is there a more pythonic way?

killian95
  • 803
  • 6
  • 11

1 Answers1

0

First try ... enumerate will help. I vote against a one-liner, because readibility counts

a = [1, 5, 2, 8]

sorted_tuples = sorted(enumerate(a), key= lambda x: x[1], reverse=True)
print([index for index, value in sorted_tuples])
Gelineau
  • 2,031
  • 4
  • 20
  • 30