no more comparisons

Dan Bishop danb_83 at yahoo.com
Thu Mar 13 21:32:47 EDT 2008


On Mar 13, 7:38 pm, Alan Isaac <ais... at american.edu> wrote:
> Mark Dickinson wrote:
> > Sorting tuples, where the second item in the tuple should
> > have the opposite ordering to the first is going to be
> > a bit of a pain.  Or even worse, where the ordering of the
> > second item depends on the value of the first item in the
> > tuple.
>
> This is like some examples where I had used cmp,
>
> but if I understand correctly I think it is not a problem.
>
> > For example, suppose that (for whatever contrived reason)
> > you're representing integers in (sign, magnitude) format
> > by tuples (s, i), where s = 0 or 1 (0 for positive, 1 for
> > negative) and i is a string representing the absolute
> > value of the integer.  So
>
> Does this do it? ::
>
>     key= lambda x: (-x[1],int(x2))
>
> Here I am depending on the lexicographic sorting of tuples.
> Without that there would be real trouble.

Even assuming you meant (-x[0], int(x[1])), that sorts negative
numbers in the wrong order.  You want

key = lambda x: (-1 if x[0] else 1) * int(x[1])



More information about the Python-list mailing list