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

如何从TXT文件中获取最大整数所在行的上一行内容?

解决方法

你的问题核心是没把分数和对应的名字关联起来,原代码硬编码行号的方式既不灵活也没保存上一行的名字。下面给两种实用的修改方案:

方案一:按组读取(推荐)

直接每次读取两行,一行是名字一行是分数,天然对应,不用管行号:

with open("r.txt", 'r') as f:
    highest_score = 0
    highest_player = ""
    # 把文件行转成迭代器,方便逐组取数
    line_iter = iter(f)
    while True:
        try:
            # 读取名字行,去掉首尾空白(比如换行符)
            player = next(line_iter).strip()
            # 读取对应的分数行,转成整数
            score = int(next(line_iter).strip())
            # 比较更新最高分和对应玩家
            if score > highest_score:
                highest_score = score
                highest_player = player
        except StopIteration:
            # 没有更多行时退出循环
            break

print(highest_player, highest_score)

这个方法的好处是不依赖固定行数,不管文件里有多少组玩家和分数都能处理,逻辑也更直观。

方案二:记录上一行内容

如果想保留遍历每一行的方式,可以用变量记录上一行的名字,遇到分数行时关联起来:

with open("r.txt", 'r') as f:
    highest_score = 0
    highest_player = ""
    last_name = ""  # 存储上一行的玩家名字

    for idx, line in enumerate(f):
        line = line.strip()
        if idx % 2 == 0:
            # 偶数索引(0、2、4...)是名字行,存起来
            last_name = line
        else:
            # 奇数索引是分数行,转成整数后比较
            current_score = int(line)
            if current_score > highest_score:
                highest_score = current_score
                highest_player = last_name

print(highest_player, highest_score)

原代码的问题说明

  1. 硬编码line_numbers = [1,3,5],如果文件行数变化(比如新增玩家)就会失效;
  2. 没有保存上一行的名字,导致highestPlayer始终是空字符串;
  3. highestScore = line保存的是字符串类型,后续比较和打印都容易出问题,应该转成整数;
  4. 手动判断i > 5终止循环没必要,文件遍历到末尾会自动停止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:11:09