[Tutor] [Fwd: Re: Extending a list within a list comprehension]

Victor Bouffier victor at grupocdm.com
Wed Apr 12 01:14:41 CEST 2006

I sent this to John directly.
Posting to the list.

-------- Forwarded Message --------
From: Victor Bouffier <victor at grupocdm.com>
To: John Fouhy <john at fouhy.net>
Subject: Re: [Tutor] Extending a list within a list comprehension
Date: Tue, 11 Apr 2006 18:03:41 -0500

On Wed, 2006-04-12 at 10:29 +1200, John Fouhy wrote:
> On 12/04/06, Victor Bouffier <victor at grupocdm.com> wrote:
> > elements = [
> > (codigo, [ cant, importe, porc]),
> > (codigo, [ cant, importe, porc]),
> > ...
> > ]
> >
> > And I want to sort descending on 'importe', which is x[1][1] for x in
> > elements.
> In python 2.4, you could achieve this by saying:
> elements.sort(key=lambda x: x[1][1])
> In earlier versions of python, you can do:
> elements.sort(lambda x, y: cmp(x[1][1], y[1][1]))
> (but this is less efficient than key= in 2.4)
> There's also the decorate-sort-undecorate idiom:
> dec = [(x[1][1], x) for x in elements]
> dec.sort()
> elements = [x[1] for x in dec]

Hi John,

Thanks for your help. This is very nice and I will definitely use it
when sorting a fixed list.
However, I forgot to point out I am including an extra element: item
description from a dict, where its key=codigo (x[0]). This is why I
write the whole list as a single element.

Still I could follow your suggestion and do:

dec = [(x[1][1], x, description[x[0]]) for x in elements]
elements = [x[1], x[2] for x in dec]

It is still better, but not quite there. Any feedback will be gladly


More information about the Tutor mailing list