Multiple "cmp"s chained one after another
Robert Kern
rkern at ucsd.edu
Sat May 14 08:47:19 EDT 2005
Volker Grabsch wrote:
> Hello!
>
> Ich just found a very nice 'pythonic' solution for an often appearing
> problem. I didn't find it documented anywhere, so I'm posting it here.
> If this isn't new in any way, I'd really like to get to know it.
>
> Example problem:
> I have some "datetime" objects and want to sort them, as here:
>
> birthdays = [d1,d2,d3,d4]
> birthdays.sort()
>
> However, I don't want to sort them the default way. These are birthdays,
> so only the month and day do matter, not the year. E.g.:
>
> 2003-01-01 should be smaller than 1984-05-01
[snip]
> Any opinions?
I find that using the "key" argument to sort is much nicer than "cmp"
for these tasks.
In [5]:L = [datetime.date(2005,5,2), datetime.date(1984,12,15),
datetime.date(1954,1,1)]
In [7]:L.sort(key=lambda x: (x.month, x.day))
In [8]:L
Out[8]:
[datetime.date(1954, 1, 1),
datetime.date(2005, 5, 2),
datetime.date(1984, 12, 15)]
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list