Question on sort() key function

Robert Latest boblatest at yahoo.com
Tue Jan 22 10:56:55 CET 2008


Peter Otten wrote:
> Robert Latest wrote:
>
>> Paul Rubin wrote:
>>> The attribute is on instances of File, not on the class itself.  See
>>> if this works:
>>>
>>>    flist.sort(key=lambda f: f.mod_date.toordinal)
>> 
>> It doesn't throw an error any more, but neither does it sort the list. This, 
>> however, works:
>> 
>> ----------------------
>> def by_date(f1, f2):
>> 	return f1.mod_date.toordinal() - f2.mod_date.toordinal()
>> 
>> flist.sort(by_date)
>> ----------------------
>> 
>> So I'm sticking with it, although I sort of liked the key approach.
>> 
>> robert
>
> This should work then:
>
> def date_key(f):
>     return f.mod_date.toordinal()
> flist.sort(key=date_key)
>
> This can also be written as
>
> flist.sort(key=lambda f: f.mod_date.toordinal())

Well, that's almost Paul's (non-working) suggestion above, but it works 
because of the parentheses after toordinal. Beats me how both versions can 
be valid, anyway.

To me it's all greek. I grew up with C function pointers, and they 
always work.

robert



More information about the Python-list mailing list