0

a = [1,3,5,2,7]

sorted a = [7,5,3,2,1]

b = [4,2,1,3,0]

I want to make a list like b

yooons
  • 107
  • 6

4 Answers4

2

A base python approach:

a = [1,3,5,2,7]
b = [i for i,_ in sorted(enumerate(a),key = lambda p: p[1],reverse = True)]
print(b) #[4, 2, 1, 3, 0]
John Coleman
  • 51,337
  • 7
  • 54
  • 119
1

Using numpy's argsort

np.argsort([1,3,5,2,7]) 

array([0, 3, 1, 2, 4])
Pygirl
  • 12,969
  • 5
  • 30
  • 43
  • 1
    `argsort` looks useful, hadn't seen it before. But you probably want `np.argsort(a)[::-1]` to reverse the order as desired in the question. – Mark Ransom Mar 11 '21 at 16:23
1

Pair each element with its index, sort the pairs and then extract the index.

>>> a = [1,3,5,2,7]
>>> b = [e[0] for e in sorted(enumerate(a), key=lambda x:x[1], reverse=True)]
>>> b
[4, 2, 1, 3, 0]
Holloway
  • 6,412
  • 1
  • 26
  • 33
0
>>> a = [1,3,5,2,7]
>>> b = sorted(range(len(a)), key=lambda i:a[i], reverse=True)
>>> b
[4, 2, 1, 3, 0]

Similar to some other answers provided, this one uses a lambda function as the sort key. This one differs by producing a list of indexes and sorting it directly, rather than pairing each value with an index and stripping out those values at the end. That makes it simpler.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622