You need to enable JavaScript to run this app. Python读取文本文件统计选手累计得分 代码计算逻辑有误
优惠活动
大模型
产品
解决方案
定价
更多

Python读取文本文件统计选手累计得分 代码计算逻辑有误

代码问题定位与修正

核心问题梳理

  • 缩进层级错误:原代码中读取文件、逐行计算、结果打印的逻辑没有正确包裹在reading()函数内部,代码结构散乱,边界不清晰。
  • 缺失类型转换:拆分文本行得到的score默认是字符串类型,直接做加法会触发字符串拼接操作,无法得到有效的数值计算结果。
  • 累加逻辑完全偏差:原代码处理已存在的选手时,执行的是dict[name] = score + score,由于没有类型转换,这里是将当前行的得分字符串重复拼接两次后覆盖原有存储值,完全没有读取选手之前的累计得分做加法,根本不具备累计统计的能力——逐行推演后完全匹配实际错误输出:
    • 逐行执行到最后,每个选手的字典值都会被最后一次出现时的得分覆盖为重复拼接的字符串,最终aps为'25'、essi为'1'拼接两次得到'11'、pietari为'7'拼接两次得到'77',和实际错误输出完全一致。
  • 输出格式缺失:预期输出开头需要打印标题行Contestant score:,原代码遗漏了这部分内容。
  • 变量名不规范:原代码用dict作为字典变量名,会覆盖Python内置的dict类型,存在潜在风险。

修正后的可运行代码

def reading():
    """
    reads input file name and open it, split lines from text in 2.
    do the calculation, print out the dictionary
    :return: dict.
    """
    file1 = input("Enter the name of the score file: ")
    # 使用with语句自动管理文件关闭,避免手动调用close()的遗漏问题
    with open(file1, mode="r") as read_file:
        score_dict = {}
        for line in read_file:
            # 去除行尾换行符
            line = line.rstrip()
            # 拆分姓名和得分,将得分转为整数类型用于数值计算
            name, score_str = line.split(" ")
            score = int(score_str)
            # 正确的累加逻辑:已存在则累加当前得分,不存在则初始化
            if name not in score_dict:
                score_dict[name] = score
            else:
                score_dict[name] += score
    # 打印要求的标题行
    print("Contestant score:")
    # 按字典序排序后逐行输出结果
    for contestant in sorted(score_dict.keys()):
        print(f"{contestant} {score_dict[contestant]}")

def main():
    reading()

if __name__ == "__main__":
    main()

修正后运行效果

使用给定的测试文本文件运行后,输出完全匹配预期:

Contestant score:
aps 25
essi 8
pietari 26

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 14:06:03