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

Python读取外部分数文件并排序展示前五高分问题求助

问题描述

我需要从外部文件读取分数,展示当前分数和前五高分,还要按从高到低排序(比如50 , Andrew是最高分,其次0 , Andrew),但一直搞不定。试过冒泡排序、按逗号分割数据降序排序都失败了,这是学校项目,急需帮忙。

文件格式示例:

-10 , Kevin
10 , Andrew
100 , Antonio 

我目前的代码:

score = 0
open("score.txt")
scorefile = open("score.txt", "r")
file_contents = scorefile.read()
leaderboard = file_contents.split(",")
leaderboard = file_contents.split("\n") 

解决方案

1. 先正确解析文件数据

你当前的代码重复分割了数据,而且没处理空行和格式细节(比如逗号前后的空格)。首先要逐行读取,把每行拆成整数类型的分数和名字,因为只有数字才能正确排序。

代码示例:

# 读取并解析历史分数
historical_scores = []
try:
    with open("score.txt", "r") as scorefile:
        for line in scorefile:
            # 去掉每行首尾的空格、换行符
            clean_line = line.strip()
            # 跳过空行
            if not clean_line:
                continue
            # 按逗号分割,再清理每个部分的空格
            score_str, name = clean_line.split(",")
            score = int(score_str.strip())
            name = name.strip()
            # 把(分数, 名字)存入列表
            historical_scores.append( (score, name) )
except FileNotFoundError:
    # 如果文件不存在,直接返回空列表
    pass

2. 用内置函数排序(比冒泡排序简单可靠)

Python自带的sorted()函数可以直接按分数降序排序,不需要自己写冒泡排序:

# 按分数从高到低排序
sorted_scores = sorted(historical_scores, key=lambda x: x[0], reverse=True)

3. 展示前五高分和当前分数

假设游戏生成的当前分数是current_score,玩家名字是current_name,先把它加入列表再排序,然后输出结果:

# 假设当前游戏生成的分数和名字
current_score = 50
current_name = "Andrew"

# 把当前分数加入总列表并重新排序
all_scores = sorted_scores.copy()
all_scores.append( (current_score, current_name) )
all_scores = sorted(all_scores, key=lambda x: x[0], reverse=True)

# 输出前五高分
print("=== 前五高分排行榜 ===")
# 取前5个,或者列表长度(如果不足5个)
for i in range(min(5, len(all_scores))):
    score, name = all_scores[i]
    print(f"{i+1}. {score} , {name}")

# 输出当前分数的排名
current_rank = next(i+1 for i, (s, n) in enumerate(all_scores) if s == current_score and n == current_name)
print(f"\n你的分数:{current_score} , {current_name}")
print(f"当前排名:第{current_rank}位")

4. 动态更新分数文件

游戏结束后,把当前分数追加到文件里:

with open("score.txt", "a") as scorefile:
    scorefile.write(f"{current_score} , {current_name}\n")

完整可运行代码

def load_historical_scores():
    """加载历史分数列表"""
    scores = []
    try:
        with open("score.txt", "r") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                score_str, name = line.split(",")
                scores.append( (int(score_str.strip()), name.strip()) )
    except FileNotFoundError:
        pass
    return scores

def save_new_score(score, name):
    """把新分数追加到文件"""
    with open("score.txt", "a") as f:
        f.write(f"{score} , {name}\n")

def show_leaderboard(current_score, current_name):
    """展示排行榜和当前分数排名"""
    # 加载历史分数
    historical = load_historical_scores()
    # 合并并排序所有分数
    all_scores = sorted(historical + [(current_score, current_name)], key=lambda x: x[0], reverse=True)
    
    # 输出前五高分
    print("=== 前五高分排行榜 ===")
    for idx in range(min(5, len(all_scores))):
        s, n = all_scores[idx]
        print(f"{idx+1}. {s} , {n}")
    
    # 输出当前排名
    rank = next(i+1 for i, (s, n) in enumerate(all_scores) if s == current_score and n == current_name)
    print(f"\n你的分数:{current_score} , {current_name}")
    print(f"当前排名:第{rank}位")

# 游戏流程示例
if __name__ == "__main__":
    # 替换成游戏生成的实际分数和玩家名字
    current_score = 75
    current_name = "Andrew"
    
    # 保存当前分数
    save_new_score(current_score, current_name)
    # 展示排行榜
    show_leaderboard(current_score, current_name)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:17:49