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?
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).
Even shorter is to use a lambda as the callable
max([a, b, c, d], key=lambda t: t[1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With