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

Python游戏高分榜:sorted()函数仅按数字首字符排序的问题求助

Python游戏高分榜排序异常修复方案

问题根源:你当前是对字符串内容直接排序,而非按分数的数值大小排序。readlines()读取的每一行都是字符串,sorted()默认按字符的ASCII顺序比较,所以会出现"9" > "10"的情况(因为字符'9'的ASCII值大于'1')。

修复步骤:

  • 读取文件内容后,将每一行拆分为分数(转换为整数类型)和玩家名称
  • 使用sorted()的key参数指定按分数的数值进行排序
  • 优化文件操作方式,避免手动关闭文件的疏漏

修正后的代码:

def enter_high_score():
    print()
    name = input("Please Enter Your Name: ")
    # 用with语句自动管理文件,无需手动close
    with open("score.txt", "a") as file:
        file.write(f"9000\t{name}\n")
    
    # 读取并处理分数数据
    scores = []
    with open("score.txt", "r") as file:
        for line in file:
            # 去除换行符,拆分分数和名字
            line = line.strip()
            if not line:
                continue
            score_str, player_name = line.split("\t")
            # 转换分数为整数,存入列表
            scores.append((int(score_str), player_name))
    
    # 按分数数值降序排序
    sorted_scores = sorted(scores, key=lambda x: x[0], reverse=True)

    print("Top 5 Scores!")
    print("Pos\tPoints\tName")

    # 遍历前5名,避免文件行数不足5时报错
    for pos, (score, name) in enumerate(sorted_scores[:5], start=1):
        print(f"{pos}\t{score}\t{name}")

关键代码解释:

  1. 文件操作优化:使用with open(...)上下文管理器,文件会在代码块结束后自动关闭,避免资源泄漏。
  2. 数据转换:将读取到的分数字符串score_str转换为整数int(score_str),这样排序时会按数值大小比较。
  3. 排序规则:sorted()的key=lambda x: x[0]指定按元组的第一个元素(即分数数值)作为排序依据,reverse=True实现从高到低排序。
  4. 安全遍历:用enumerate(sorted_scores[:5], start=1)只取前5条数据,即使文件中分数记录不足5条也不会抛出索引越界错误。

内容的提问来源于stack exchange,提问作者Jim Lister

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:21:02