Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max of the 2nd element in a tuple - Python

Given a tuple list, i can find the max of the 1st element in the tuple list by:

>>> a,b,c,d = (4,"foo"),(9,"bar"),(241,"foobar"), (1,"barfoo")
>>> print max([a,b,c,d])
(241,"foobar")

But how about finding the max of the 2nd element? and how about the max of a string?

like image 544
alvas Avatar asked Jan 15 '23 14:01

alvas


2 Answers

Use the key parameter:

import operator

max([a, b, c, d], key=operator.itemgetter(1))

The max() of a string is based on the byte values of the string; 'a' is higher than 'A' because ord('a') is higher than ord('A').

For your example input, (241,"foobar") is still the max value, because 'f' > 'b' and 'foobar' is longer (more values) than 'foo', and 'b' > '' (with b being the character following the letters foo in the longer string).

like image 109
Martijn Pieters Avatar answered Jan 17 '23 04:01

Martijn Pieters


Even shorter is to use a lambda as the callable

max([a, b, c, d], key=lambda t: t[1])
like image 33
Olaf Avatar answered Jan 17 '23 03:01

Olaf