【问题标题】:Get the key with the biggest score in Python [duplicate]获取Python中得分最高的密钥[重复]
【发布时间】:2019-06-09 17:42:11
【问题描述】:

我想知道您是否知道其他/更好的方法(没有 max 方法)来获取字典中得分最高的键? :

report_card = {'french' : 14,
            'english' : 12,
            'math' : 16,
            'chemistry' : 19,
            'sport' : 14}
max = 0

for subject, score in report_card.items():
    if max < report_card[subject]:
        max = report_card[subject]

for subject, score in report_card.items():
    if max == report_card[subject]:
        print(f"The subject with the highest score is {subject} with {score} points")

【问题讨论】:

  • 为什么没有 max 函数?
  • 保持你正在做的跑步最大值可能是最好的方法
  • Getting key with maximum value in dictionary? 的可能重复项。此线程上至少有 4 或 5 个答案不使用max
  • 我不想使用“max”来训练我的逻辑和娱乐(我开始编程)

标签: python python-3.x dictionary key key-value


【解决方案1】:

有点简单,但是请注意,max 函数的存在是有原因的。

report_card = {'french' : 14,
            'english' : 12,
            'math' : 16,
            'chemistry' : 19,
            'sport' : 14}
max = 0
max_s = ""

for subject, score in report_card.items():
    if max < score:
        max = score
        max_s = subject

print(f"The subject with the highest score is {max_s} with {max} points")

【讨论】:

    【解决方案2】:

    试试这个:

    max(report_card.items(), key=lambda x: x[1])[0]
    

    dict.items() 将所有值成对返回。 max 返回可迭代的最大值。 key 关键字允许您传递函数,该函数为每个项目生成值以比较最大值。 max 函数将返回 report_card.items() 生成的值之一(不是 key 函子生成的值),因此您需要 [0] 从中获取密钥。

    【讨论】:

    • 谢谢拉多斯劳
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多