list conversion question

Raymond Hettinger python at rcn.com
Sat Sep 4 20:24:19 EDT 2004


[Peter Otten] 
> >    Even faster, though perhaps not as clear:
> > 
> >      >>> import operator
> >      >>> hist = [ 0, 1, 0, 5, 43 ]
> >      >>> map(operator.itemgetter(0), sorted(enumerate(hist),
> >      ...                             key=operator.itemgetter(1)))
> >      [0, 2, 1, 3, 4]
>  
> Yet another option, not benchmarked, perhaps clearer:
> 
> >>> hist = [0, 1, 0, 5, 43]
> >>> indices = range(len(hist))
> >>> indices.sort(key=hist.__getitem__)
> >>> indices
> [0, 2, 1, 3, 4]

These are both fast and clean.  Consider posting them to the ASPN
cookbook so they won't get lost.


Raymond Hettinger



More information about the Python-list mailing list