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
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]
Using numpy's argsort
np.argsort([1,3,5,2,7])
array([0, 3, 1, 2, 4])
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]
>>> 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.