Multiple "cmp"s chained one after another

Steven Bethard steven.bethard at gmail.com
Sat May 14 11:13:17 EDT 2005


Robert Kern wrote:
> 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)]

Yes, definitely.  Also worth noting in Robert Kern's solution is that 
instead of writing:

     def mycmp(d1, d2):
         return cmp(d1.month,d2.month) or cmp(d1.day,d2.day)

you can write:

     def mycmp(d1, d2):
         return cmp((d1.month, d1.day), (d2.month, d2.day))

or if you're using the key= argument (like you probably should):

     def mykey(d):
         return (d.month, d.day)

The point here is that rather than chaining cmp() calls with ors, you 
should just use a tuple -- the standard comparison order in tuples is 
exactly what you're looking for.

STeVe



More information about the Python-list mailing list