python内置函数max的用法是:
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
通常用:
d = {'a': 1, 'b': 3, 'c': 2}
result = max(d, key=d.get)
print(result) ### 'b'
找出字典中的最大值对应的键。
分析:
这里是通过max函数中的key参数指定一个函数,然后迭代取出可迭代对象的元素,这里由于python直接对字典操作的话其实用的是字典的键,因此就是迭代获得items: ‘a’,‘b’,‘c’,然后作为key指定的函数的参数,得到val: d.get(‘a’),d.get(‘b’),d.get(‘c’)。通过比较val,返回最大的val对应的item,即d.get(‘b’)最大,返回’b’。
这一点可以从对应的cpython代码中看出(省略了一些错误判断语句):
...
maxitem = NULL; /* the result */
maxval = NULL; /* the value associated with the result */
while (( item = PyIter_Next(it) )) {
/* get the value from the key function */
if (keyfunc != NULL) {
val = PyObject_CallOneArg(keyfunc, item); // 这里将item作为keyfunc的参数得到返回值
...
}
/* no key function; the value is the item 如果不指定key,val就直接等于item */
else {
val = item;
...
}
/* maximum value and item are unset; set them */
if (maxval == NULL) {
maxitem = item;
maxval = val;
}
/* maximum value and item are set; update them as necessary */
else {
int cmp = PyObject_RichCompareBool(val, maxval, op);
...
else if (cmp > 0) { // 这里大于0就是意味着现在的val大于maxval,则替换maxval
...
maxval = val;
maxitem = item;
}
...
}
}
}
因此max(d, key=d.get)
也可以写为max(d, key=lambda x: d[x])
同理,如果需要获取最大值对应的键值对:
则max(d.items(), key=lambda x: x[1])
这里即是把(‘a’, 1),(‘b’, 3),(‘c’, 2)作为函数的输入x,比较x[1]即1,3,2的值,返回最大值3对应的元素(‘b’, 3)。
总结来说 :key参数就是将输入的可迭代对象中的每个元素,通过key指定的函数进行转换,比较转换后的值,最后返回转换后的最大值对应的原先的元素。