copysort patch, was RE: [Python-Dev] inline sort option
Alex Martelli
aleaxit at yahoo.com
Sat Oct 18 16:01:52 EDT 2003
On Saturday 18 October 2003 09:13 pm, Dan Aloni wrote:
...
> > >> Guido> keys = D.keys()
> > >> Guido> keys.sort()
> > >> Guido> for key in keys:
...
> Actually, there is way to do this out-of-the-box without the chain()
>
> function:
> >>> a = [1,2,3,3,2,1]
> >>> (a, (a, a.sort())[0].reverse())[0]
This cannot be applied to D.keys() for some directory D.
> >>> (lambda x:(x, x.sort())[0])(list(a))
This one can, because the lambda lets you give a temporary name x
to the otherwise-unnamed list returned by D.keys(). It can be made a
_little_ better, too, I think:
>>> D=dict.fromkeys('ciao')
>>> D.keys()
['i', 'a', 'c', 'o']
>>> (lambda x: x.sort() or x)(D.keys())
['a', 'c', 'i', 'o']
and if you want it reversed after sorting,
>>> (lambda x: x.sort() or x.reverse() or x)(D.keys())
['o', 'i', 'c', 'a']
> But that's probably not more readable.
You have a gift for understatement. Still, probably more readable than
the classic list comprehension hack:
>>> [x for x in [D.keys()] for y in [x.sort(), x] if y][0]
['a', 'c', 'i', 'o']
also, the lambda hack doesn't leak names into the surrounding scope,
while the list comprehension hack, alas, does.
BTW, welcome to python-dev!
Alex
More information about the Python-Dev
mailing list