[Tutor] Extending a list within a list comprehension
John Fouhy
john at fouhy.net
Wed Apr 12 00:29:55 CEST 2006
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]
--
John.
More information about the Tutor
mailing list