获得 Python 中得分最高的钥匙

Get the key with the biggest score in Python

我想知道您是否知道 other/better 获取字典中得分最高的键的方法(没有 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 函数的存在是有原因的。

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")

试试这个:

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

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