How is max supposed to work, especially key.
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Dec 4 06:55:33 EST 2014
Jussi Piitulainen wrote:
> Would you also want sorted called something else when used with a key?
> Because it doesn't produce a sorted list of the keys either:
>
> >>> data = ("short", "long", "average")
> >>> sorted(data, key=len)
> ['long', 'short', 'average']
> >>> max(data, key=len)
> 'average'
I agree with the point you are making, but I disagree with the wording you
use. The result of calling sort() with key=len *is* sorted. It is sorted by
length of the word.
Same for calling max() with a key. The result is still the maximum value.
The difference is how you decide which of two elements is greater:
max(list_of_foods, key=calories)
max(list_of_foods, key=weight)
max(list_of_foods, key=cost)
That is three different ways to decide which is the maximal food in the
list: by number of calories, by weight, or by cost.
--
Steven
More information about the Python-list
mailing list