【问题标题】:How can I find the max value from a dictionary?如何从字典中找到最大值?
【发布时间】:2019-04-04 01:17:12
【问题描述】:

你好,这是我第一次使用 python

我有一本字典:

players= {"Gehrig":{"atBats":8061, "hits":2721},
 "Ruth":{"atBats":8399, "hits":2873},
 "Williams":{"atBats":7706, "hits":2654}}

我想找出三个玩家中任何一个的命中率最高。

期望的输出:

The most hits by one of the
players was 2873.

我的意见:

max(players.hits())
maximum = max(players,key=players.get)
max(players,key=players.get)

但我只收到如下错误:

TypeError: '>' not supported between instances of 'dict' and 'dict'

我需要改变什么?

【问题讨论】:

    标签: python dictionary syntax max


    【解决方案1】:

    您想使用列表推导式或生成器表达式仅遍历命中数:

    players= {"Gehrig":{"atBats":8061, "hits":2721},
     "Ruth":{"atBats":8399, "hits":2873},
     "Williams":{"atBats":7706, "hits":2654}}
    
    max(player["hits"] for player in players.values())
    # 2873
    

    如果您想查看哪个玩家的点击次数最多:

    max(players.keys(), key=lambda p: players[p]["hits"])
    # 'Ruth'
    

    【讨论】:

    • 嗨,Tom,我是 python 新手,你能解释一下“players.values())”中的语法吗?
    • @lilzuzu 它只是返回字典中的所有值。例如,{'a': 1, 'b': 2, 'c': 3}.values() 将是 [1, 2, 3]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2022-08-14
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多