# Re: seemingly simple list indexing problem

Discussion in 'Python' started by Guilherme Polo, Jul 28, 2008.

1. ### Guilherme PoloGuest

On Mon, Jul 28, 2008 at 6:24 PM, 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]

You could simply do this:

a = [108, 58, 68]
b = sorted(a)
[b.index(c) for c in a]

>
> 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
>

--
-- Guilherme H. Polo Goncalves

Guilherme Polo, Jul 28, 2008

2. ### Raymond HettingerGuest

[Ervan Ensis]
> 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]

One solution is to think of the list indexes
being sorted according the their corresponding
values in the input array:

>>> s = [ 108, 58, 68 ]
>>> sorted(range(len(s)), key=s.__getitem__)

[1, 2, 0]

Raymond

Raymond Hettinger, Jul 29, 2008

3. ### Guest

On 29 Jul., 01:05, Raymond Hettinger <> wrote:
> [Ervan Ensis]
>
> > 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]

>
> One solution is to think of the list indexes
> being sorted according the their corresponding
> values in the input array:
>
> >>> s = [ 108, 58, 68 ]
> >>> sorted(range(len(s)), key=s.__getitem__)

>
> [1, 2, 0]
>

To get the desired output you have to apply it twice:
>>> sorted(range(len(s)), key=sorted(range(len(s)), key=s.__getitem__).__getitem__)

[2, 0, 1]

Wolfram

, Jul 30, 2008
4. ### John KrukoffGuest

On Wed, 2008-07-30 at 14:08 -0700,
wrote:
> On 29 Jul., 01:05, Raymond Hettinger <> wrote:
> > [Ervan Ensis]
> >
> > > 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]

> >
> > One solution is to think of the list indexes
> > being sorted according the their corresponding
> > values in the input array:
> >
> > >>> s = [ 108, 58, 68 ]
> > >>> sorted(range(len(s)), key=s.__getitem__)

> >
> > [1, 2, 0]
> >

>
> To get the desired output you have to apply it twice:
> >>> sorted(range(len(s)), key=sorted(range(len(s)), key=s.__getitem__).__getitem__)

> [2, 0, 1]
>
> Wolfram
> --
> http://mail.python.org/mailman/listinfo/python-list

Thanks, I knew I was missing something simpler.
--
John Krukoff <>
Land Title Guarantee Company

John Krukoff, Jul 30, 2008