[python] max函数中key参数的使用

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指定的函数进行转换,比较转换后的值,最后返回转换后的最大值对应的原先的元素。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值