On 18-Jan-08, at 1:37 PM, Lars Immisch wrote:
>
> I like cmp, too. I've looked through my code, and I've only used it in
> script-ish circumstances, but here is an example that sorts a list of
> files by modification date:
>
> def cmp_mtime(f, g):
> """Too much for a lambda for my tastes."""
> return cmp(os.stat(f).st_mtime, os.stat(g).st_mtime)
>
> files = os.listdir('.')
> files.sort(cmp_mtime)
The use case of sort-function delegating to cmp() of part of an
object is covered by the key= parameter, which is faster and more
succinct:
files = os.listdir('.')
files.sort(key=lambda f: os.stat(f).st_mtime)
Grepping though my team's codebase, I see some uses similar to yours
above, but all can be replaced with key=. Personally, I don't see
the attraction of writing sort functions this way: I fell in love
with key= the moment I discovered it.
The relative frequency is 84 key-based sorts to 9 cmp()-based sorts
(admittedly that is more due to my influence than to a natural
distribution).
-Mike
_______________________________________________
Python-3000 mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe:
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com