seemingly simple list indexing problem

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


On Mon, 2008-07-28 at 15:00 -0700, Gary Herron wrote:
> Guilherme Polo wrote:
> > On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis <ervan.ensis at gmail.com> 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]
> >>     
> >
> > You could simply do this:
> >
> > a = [108, 58, 68]
> > b = sorted(a)
> > [b.index(c) for c in a]
> >   
> 
> Yuck.  Slow, and it fails if duplicate list elements exist.
> 
> Also...  This looks like a beginners programming assignment.    Let's 
> let him try it himself.  We can offer help rather than full solutions if 
> he has specific Python questions.
> 
> 
> 
> 
> 
> >   
> >> 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
> >>
> >>     
> >
> >
> >
> >   
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

Sorry, problem was interesting to solve, so I may have jumped the gun. I
do wonder why OP was asking for this though, as now that you mention it
I can't think of a use case outside of a homework assignment.

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




More information about the Python-list mailing list