How do I sort a list of indices by what they'r开发者_JAVA百科e pointing to in python?
I have
indices = list(range(len(mylist)))
I want to sort the indices so that if a
precedes b
in indices then mylist[a] > mylist[b]
.
indicies.sort(lambda x,y:mylist[x]-mylist[y])
Also, let me add the following snippet as an answer, using the information provided in your original question...
I want to sort the indices so that if a precedes b in indices then mylist[a] > mylist[b].
...and the additional info you have in your comment
Also, what if mylist is a list of numpy floats?
Then you can simply do:
In [2]: import numpy
In [3]: a = numpy.asarray([-1, 2.73, 15.827, -8.48, 9, 13, 15, 3.22, 0, -1, 1])
In [4]: indices = a.argsort()[::-1]
Out[4]: array([ 2, 6, 5, 4, 7, 1, 10, 8, 9, 0, 3])
In [5]: a[indices]
Out[5]:
array([ 15.827, 15. , 13. , 9. , 3.22 , 2.73 , 1. ,
0. , -1. , -1. , -8.48 ])
Python 2.6+, most elegant answer:
indices.sort(key = lambda x:mylist[x], reverse = True)
精彩评论