anonymous variable

Alex Martelli aleaxit at yahoo.com
Sat Jul 7 17:05:17 EDT 2001


"Emmanuel Jeandel" <ejeandel at ens-lyon.fr> wrote in message
news:9i791n$3bh$1 at macareux.ens-lyon.fr...
> Hello
>
> In a script i made, i have tuples (name, nb, size) in a list and i wanted
to
> sort the list with respect to size.

As an aside, you know the fastest way for this is almost invariably:

    templist = [(size,tuple) for tuple in alist for _,_,size in tuple,]
    templist.sort()
    alist[:] = [tuple for size, tuple in templist]

AKA decorate-sort-undecorate, didn't you?  That doesn't affect your
argument, I'm just pointing out once again that passing a function
to .sort() is almost never optimal... hmm, maybe we could have a
way to encapsulate THIS excellent pattern in a perhaps-handier
way... the only real variant is the decoration, so we might have:

def dsu_sort(alist, decorate):
    templist = [(decorate(item),item) for item in alist]
    templist.sort()
    alist[:] = [item for _,item in templist]

and you could call
    dsu_sort(alist, lambda x: x[2])
to satisfy lambda-craving, or, more readably:
    def bysize(tuple): return tuple[2]
    dsu_sort(alist, bysize)
or perhaps nicer:
    def bysize(tuple): _,_,size=tuple; return size
and in any case the pattern would be well-packaged.


Alex






More information about the Python-list mailing list