sorting list and then return the index of the sorted item

F. Petitjean littlejohn.75 at news.free.fr
Tue May 3 09:55:43 EDT 2005


Le 3 May 2005 06:37:14 -0700, custard_pie a écrit :
> I need help sorting a list...I just can't figure out how to sort a list
> and then return a list with the index of the sorted items in the list
> for example if the list I want to sort is [2,3,1,4,5]
> I need [2,0,1,3,4] to be returned
> Can someone help please....
If you have Python version 2.4 (or 2.4.1):
lst = [2,3,1,4,5]
import operator
sorted(enumerate(lst), key=operator.itemgetter(1))
[(2, 1), (0, 2), (1, 3), (3, 4), (4, 5)]

But *why* do you want the indices ? Most of the time dealing with the
indices is the wrong way in Python (perhaps the right way in FORTRAN :-)



More information about the Python-list mailing list