# list conversion question

Paul McGuire ptmcg at austin.rr._bogus_.com
Sat Sep 4 18:39:28 CEST 2004

```"Andrew Dalke" <adalke at mindspring.com> wrote in message
> Paul McGuire wrote:
> > Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] how
> >
> > hist = [ 0, 1, 0, 5, 43 ]
> > values = [ i for i in enumerate(hist)]
> > values.sort(lambda a,b: cmp(b[1],a[1]))
> > indexes = [ a for a,b in values ]
>
> or tweaked a bit for speed (a sort with a lambda is expensive)
> and for clarity, IMO,
>
> pairs = [(value, offset) for (offset, value) in enumerate(hist)]
> pairs.sort()
> indexes = [offset for (value, offset) in pairs]
>
> In Python2.4 this is allowed
>
>  >>> hist = [ 0, 1, 0, 5, 43 ]
>  >>> [pair[0] for pair in sorted(enumerate(hist),
> ...                             key=lambda pair: pair[1])]
> [0, 2, 1, 3, 4]
>  >>>
>
> Not yet sure that that's a good thing.
>
> Andrew
> dalke at dalkescientific.com

I assumed that the resulting list should be sorted in descending frequency
order.  Probably the fastest way to do this (since we are tweaking for
speed) would be to just change the pairs list comp to "pairs = [(-value,
offset) for (offset, value) in enumerate(hist)]", or your Py 2.4 key clause
from "key=lambda pair: pair[1]" to "key=lambda pair: -pair[1]".

-- Paul

```