max() of a list of tuples

Peter Abel p-abel at t-online.de
Thu Jan 23 18:03:59 EST 2003


Erik Max Francis <max at alcyone.com> wrote in message news:<3E2F37B4.C8CB8F1A at alcyone.com>...
> Peter Abel wrote:
> 
> > 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.
> 
> It's implementation defined; all strings could test greater than all
> numerics in a particular Python implementation, for instance.
> 
> > 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.
> 
> It's not clear to me why you think an initial value here is necessary in
> the first place.
When I played around with some examples, it seemed not to work without
an initial value.
>                 Since you're only doing the equivalent a reduce on a
> max function, the only case you'd need to specify that third argument is
> if there were nothing to reduce (i.e., the list were empty).
I think you're right:

>>> n=0
>>> def my_max(y,x):
... 	global n
... 	print 'y(%d)=%s'%(n,str(y))
... 	n+=1
... 	return y[2]>x[2] and y or x
... 
>>> l= [(-52, -28, -987), (-63, -16, 295), (-54, -16, 809), (-13, -3,
-14), (-97, -36, 552)]
>>> print 'Result:%s'%str(reduce(my_max,l))
y(0)=(-52, -28, -987)
y(1)=(-63, -16, 295)
y(2)=(-54, -16, 809)
y(3)=(-54, -16, 809)
Result:(-54, -16, 809)
>>> n=0
>>> l= [(-52, -28, -987), (-63, -16, -295), (-54, -16, -809), (-13,
-3, -14), (-97, -36, -552)]
>>> print 'Result:%s'%str(reduce(my_max,l))
y(0)=(-52, -28, -987)
y(1)=(-63, -16, -295)
y(2)=(-63, -16, -295)
y(3)=(-13, -3, -14)
Result:(-13, -3, -14)
>>> 
And if there's no initial value, it seems the
reduce-function starts with the first element of l.
(As I said l[0] <wink>)

>                                                             But you
> can simply handle that case separately before you call reduce, so it's a
> non-issue.
I like it compact:
>>> l=[]
>>> reduce(lambda y,x:y[2]>x[2] and y or x,len(l) and l or
[('this','is an','empty list!!')])
('this', 'is an', 'empty list!!')
>>> l= [(-52, -28, -987), (-63, -16, -295), (-54, -16, -809), (-13,
-3, -14), (-97, -36, -552)]
>>> reduce(lambda y,x:y[2]>x[2] and y or x,len(l) and l or
[('this','is an','empty list!!')])
(-13, -3, -14)
>>> 

Peter




More information about the Python-list mailing list