max() of a list of tuples

Peter Abel p-abel at t-online.de
Wed Jan 22 07:47:14 EST 2003


Martin Maney <maney at pobox.com> wrote in message news:<b0l57d$12j$1 at wheel2.two14.net>...
> Peter Abel <p-abel at t-online.de> wrote:
> > Silly me!!!
> > The correct code is:
> >>>> l = [(1, 3, 5), (8, 16, 2), (2, 56, 4)]
> >>>> reduce(lambda y,x:y[2]>x[2] and y or x,l,(-1.e16,-1.e16,-1.e16))
> > (1, 3, 5)
> 
> Why not (None,None,None) as the initial value?
> 
> (no, really, I don't know.  it just seemed natural in the same way that
> thinking "reduce is the answer" seemed as it popped into my head when I
> first saw the OP's question.  None does seem to compare as less than
> anything else (and, yeah, trying it seemed more natural than looking it
> up - I think Python may be eating my mind, but I can't bring myself to
> worry about it))

Believe me, I'm not at all happy with (-1.e16,-1.e16,-1.e16).
It's only because nothing else came into my head.
I tried ('','','') and it worked too ?? But
as I remarked later, only in this special case.
So the solution is to start with the first element of l.
And the the tuples can be what they want: integer, floats etc.

reduce(lambda y,x:y[2]>x[2] and y or x,l,l[0])

I think it's the best initial value one can choose.
Peter




More information about the Python-list mailing list