anonymous variable
Vladimir Nesterovsky
vnestr at netvision.net.il
Sat Jul 7 21:14:58 EDT 2001
It might be viewed as a "value sort" or "sort by value",
meaning that a natural sort is done on a list as if each
its element was represented by some value comparable
with the "<" operator, produced by a user-specified function:
def vsort (ls, f):
x = map(lambda e,g=f : (g(e),e), ls)
x.sort()
return map(lambda p:p[1],x)
and call it
alist = vsort(alist, lambda x: x[2])
This is doing the same thing that your function is doing by a
different syntax; knowing as little Python as I do I just don't
know which way's faster. :-)
In Perl they call it Schwartzian transform, but the paradigm's
the same in any language. I once did it to sort Lisp data by a
Lisp value-function (well, AutoLisp to be exact) in C with standard
qsort() function. How to provide for a value-element association
is a more technical detail; in C I used pointers, in Python tuples
are the readily available built-in possibility.
Cheers,
Vlad http://vnestr.tripod.com/
Alex Martelli <aleaxit at yahoo.com> wrote in message
news:9i7tjq01b9o at enews3.newsguy.com...
> "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