【问题标题】:get the key of the maximum value in the dictionary among some values [duplicate]在某些值中获取字典中最大值的键[重复]
【发布时间】:2020-03-24 05:17:50
【问题描述】:

我有一本字典:D = {'N':5, 'S':0, 'W':6, 'E':1},我想在D['N']D['S'] 中获取最大值的键。

例如,我尝试了代码 print(lambda k: max(k['N'], k['S'])(k=D.keys())),但它返回的 lambda 对象类似于 <function <lambda> at 0x000002C7B060C1E0>。虽然我想在输出中得到 N

需要帮助。谢谢!

【问题讨论】:

    标签: python dictionary lambda


    【解决方案1】:

    只需将dict.get 函数作为key 参数传递给max()

    # to find the max of entire dictionary
    
    max(D, key=D.get)
    # 'W'
    
    # to find individual keys
    
    max(['N', 'S'], key=D.get)
    # 'N'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 2011-05-27
      • 1970-01-01
      相关资源
      最近更新 更多