seemingly simple list indexing problem

John Krukoff jkrukoff at ltgc.com
Mon Jul 28 18:10:13 EDT 2008


On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote:
> My programming skills are pretty rusty and I'm just learning Python so
> this problem is giving me trouble.
> 
> I have a list like [108, 58, 68].  I want to return the sorted indices
> of these items in the same order as the original list.  So I should
> return [2, 0, 1]
> 
> For a list that's already in order, I'll just return the indices, i.e.
> [56, 66, 76] should return [0, 1, 2]
> 
> Any help would be appreciated.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

If your lists aren't so large that memory is an issue, this might be a
good place for a variation of decorate, sort, undecorate.

>>> listToSort = [ 108, 58, 68 ]
>>> decorated = [ ( data, index ) for index, data in
enumerate( listToSort ) ]
>>> decorated
[(108, 0), (58, 1), (68, 2)]
>>> result = [ None, ] * len( listToSort )
>>> for sortedIndex, ( ignoredValue, originalIndex ) in
enumerate( sorted( decorated ) ):
...     result[ originalIndex ] = sortedIndex
... 
>>> result
[2, 0, 1]

-- 
John Krukoff <jkrukoff at ltgc.com>
Land Title Guarantee Company




More information about the Python-list mailing list