list conversion question

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


"Andrew Dalke" <adalke at mindspring.com> wrote in message
news:ivb_c.6952$w%6.2458 at newsread1.news.pas.earthlink.net...
> Paul McGuire wrote:
> > Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] how
> > about:
> >
> > 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





More information about the Python-list mailing list