cmp of multiple attributes
Alex Martelli
aleaxit at yahoo.com
Wed Dec 22 14:21:18 EST 2004
Roy Smith <roy at panix.com> wrote:
> >Roy Smith wrote:
> >> def __cmp__ (self, other):
> >> # I wish there was a less verbose way to do this!
> >> if self.block < other.block:
> >> return -1
> >> if self.block > other.block:
> >> return 1
> >> if self.lot < other.lot:
> >> return -1
> >> if self.lot > other.lot:
> >> return 1
> >> return 0
>
> Steven Bethard <steven.bethard at gmail.com> wrote:
> >Does this do what you want?
> >... def __cmp__(self, other):
> >... return (cmp(self.block, other.block) or
> >... cmp(self.lot, other.lot))
>
> Yes, that's exactly what I was after. Like so many things, it's
> obvious once it's pointed out to you. Thanks!
Better still, IMHO:
def __cmp__(self, other):
return cmp((self.block,self.lot), (other.block,other.lot))
Comparisons of tuples, lists, etc, are *lexicographical*: the first
items are compared; iff they're equal, then the second items, and so
forth. IOW, exactly what you want in this case.
Alex
More information about the Python-list
mailing list