max() of a list of tuples
jepler at unpythonic.net
Tue Jan 21 23:46:34 CET 2003
On Tue, Jan 21, 2003 at 10:20:54PM -0000, Lee Harr wrote:
> > Here's another way:
[using sort with a comparison function]
> Yup, that is the way I would go also.
> Very simple & straightforward.
> (tho I might not have used a lambda ;-)
However, you can find the maximum of a list in O(n) comparisons, but you
can only sort a list in O(n log n) comparisons. I'd endorse a variant of
DSU (decorate, sort, unsort) which would be decorate, max, undecorate.
I think you were calling the largest tuple the one whose final element was
greatest, in which case the following code seems likely:
def decorate(t): return (t[-1], t)
def undecorate(t): return t
l = [decorate(t) for t in l]
More information about the Python-list