sorting list and then return the index of the sorted item

Scott David Daniels Scott.Daniels at Acm.Org
Tue May 3 15:41:00 EDT 2005


Duncan Booth wrote:
> custard_pie wrote:
> 
>>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
> 
> ...
>>>>v = [2, 3, 1, 4, 5]
>>>>import operator
>>>>[ i for (i,j) in sorted(enumerate(v), key=operator.itemgetter(1))]
> 
> [2, 0, 1, 3, 4]
> 

Or, to get fancy with Python 2.4:

     result = sorted(range(len(v)), key=v.__getitem__)

Make a list of indices, and says the sort key is "over there" to sorted.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list