简体   繁体   English

如何在值的数组中某个位置给定值的字典的最大项目?

[英]How to give the max item of a dictionary given a value somewhere in an array in the value?

In python, say I have a dictionary 在python中,说我有字典

{1:[1,333], 2:[5,22], 3:[8:0]}

I want to return the max item in the dictionary by the second item in the value array, so in this case, 333 beats all the rest numbers in the same place, I wish the function can return 我想通过值数组中的第二项返回字典中的最大项,因此在这种情况下,333击败了所有剩余数字在同一位置,我希望函数可以返回

(1,[1,33])

Is there any neat way to implement this using max() with key or something else? 是否有任何巧妙的方法可以将max()与key或其他方法一起使用?

>>> d = {1:[1,333], 2:[5,22], 3:[8, 0]}
>>> max(d.items(), key=lambda e: e[1][1])
(1, [1, 333])

You can achieve this using the key argument to max() , ie: 您可以使用max()key参数来实现这一点,即:

d = {1:[1,333], 2:[5,22], 3:[8,0]}
# Use d[k][1] so that max is based on the second
#   item in each list
max_key = max(d, key=lambda k: d[k][1])
print((max_key, d[max_key]))
(1, [1, 333])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM