Question on sort() key function

Peter Otten __peter__ at web.de
Tue Jan 22 04:30:22 EST 2008


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())

Peter



More information about the Python-list mailing list