How is max supposed to work, especially key.

random832 at fastmail.us random832 at fastmail.us
Thu Dec 4 09:09:43 EST 2014


On Thu, Dec 4, 2014, at 05:09, Albert van der Horst wrote:
> So in that case max doesn't return the maximum (True), but instead
> something else.

If you want to find the "largest" item in a list of of strings, sorted
case-insensitively, you might use str.lower or locale.strxfrm as the key
function. If two strings are case-insensitively identical, using
str.lower will return an arbitrary one (or maybe the first or last found
in the original list), using locale.strxfrm will return the one that is
in uppercase in the first position where they are different. But you
don't want it to return the all-lowercase version (or the messy binary
thing returned by strxfrm), you want it to return the string from the
original list.

Think of it this way: the key function returns a proxy object whose
comparison operators compare according to the relationship you want to
compare the originals by. Bool does not make a good proxy object.

If you want to use the original as a tiebreaker, you might use lambda x:
(str.lower(x), x).

A key function is supposed to be a function that will always return the
same result on the same input, so if you want to know "the maximum"
[i.e. the actual key value that was compared by the max function] you
can simply apply it again on the result.



More information about the Python-list mailing list