A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2003-October/038986.html below:

copysort patch, was RE: [Python-Dev] inline sort option

copysort patch, was RE: [Python-Dev] inline sort optionAlex 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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4