You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典技术问题:按字母逆序排序键并获取打印最高分

解决Python字典按键逆序排序并获取最高分的问题

嘿,我来帮你搞定这个问题!这里有个直接可行的方案,完美匹配你的需求:

完整代码示例

marks = { "Zane": [25, 58, 66, 42], "Kate": [34, 42, 86] }

# 先把字典的键值对按姓名逆序排序
sorted_by_name_reverse = sorted(marks.items(), key=lambda item: item[0], reverse=True)

# 遍历排序后的结果,提取每个姓名的最高分并打印
for name, score_list in sorted_by_name_reverse:
    best_score = max(score_list)
    print(f"{name}'s best mark is {best_score}.")

运行这段代码,你会得到和预期一致的输出:

Kate's best mark is 86.
Zane's best mark is 66.

分步解释

  • 排序字典项:用sorted()函数处理marks.items(),它会把字典转换成包含(姓名, 分数列表)的元组列表。key=lambda item: item[0]指定按元组的第一个元素(也就是姓名)排序,reverse=True则让排序结果变成字母逆序(从Z到A)。
  • 获取最高分并打印:遍历排序后的元组列表,对每个分数列表用max()函数直接拿到最高分,再用f-string格式化输出成你想要的格式。

额外优化:处理空分数列表

如果你的字典里可能存在某个姓名没有分数(空列表),可以加个简单的判断避免报错:

marks = { "Zane": [25, 58, 66, 42], "Kate": [34, 42, 86], "John": [] }

sorted_by_name_reverse = sorted(marks.items(), key=lambda item: item[0], reverse=True)

for name, score_list in sorted_by_name_reverse:
    if score_list:
        best_score = max(score_list)
        print(f"{name}'s best mark is {best_score}.")
    else:
        print(f"{name} has no recorded marks.")

这样运行后就会输出:

Zane's best mark is 66.
Kate's best mark is 86.
John has no recorded marks.

内容的提问来源于stack exchange,提问作者Mohamed Gownian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:18:10