[FRPythoneers] a more generic sort

Jack Diederich jack at performancedrivers.com
Tue Jan 21 11:11:49 MST 2003


On Tue, Jan 21, 2003 at 10:49:06AM -0700, Andrew Diederich wrote:
<snip> 
> is this even possible?  p. 1020 of Programming Python has a neat example
> with a lambda, but I don't see how I'd pass in the value into a lambda.
> 
> res.sort( lambda x, y, param: cmp(x[param], y[param]) )
> 
> The book example does essentially this:
> res.sort( lambda x, y: cmp(x['cn'], y['cn']) )

Python has essentially two scopes, local and global
lambdas can use variables in the local (function) scope.
This might not be true in 1.5.x, I know 2.2.x supports
more nuanced scoping rules.

That said, you can bind variables explicitly even in 1.5 IIRC

sort_on_me = 'cn'
res.sort(lambda a, b, param=sort_on_me: cmp(a[param], b[param]))

The scoping rules in 2.2 are more DWIM.  But it doesn't sound like
you have that option.

2.2 ex/
sort_on_me = 'cn'
res.sort(lambda a,b: cmp(a[sort_on_me], b[sort_on_me]))

Lambda's are hated by some, loved by few (me included).
Its one of the frequently flame-laden threads on c.l.py
Most people don't use them and are indifferent.

-jack

ps, ActiveState has a searchable snippet library that can
solve most small python problems for you by example.



More information about the FRPythoneers mailing list