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

如何在文件中最后一个'new('之后打印首个含'fourth'的行?

解决方案

实现思路

你用反向遍历找最后一个new(的方向是对的,但找到后需要切换逻辑:从该行在原文件的下一行开始,正向查找第一个包含fourth的行。下面提供两种高效实现方式:

代码实现

方式一:先记录所有行,定位后正向查找

with open("file.txt", "r") as fin:
    lines = fin.readlines()

# 定位最后一个含"new("的行的索引
last_new_pos = -1
for idx, line in enumerate(lines):
    if 'new(' in line:
        last_new_pos = idx

# 从目标位置后开始找第一个含"fourth"的行
if last_new_pos != -1:
    for line in lines[last_new_pos + 1:]:
        clean_line = line.strip()
        if clean_line and 'fourth' in clean_line:
            print(clean_line)
            break

方式二:反向遍历标记,即时查找

with open("file.txt", "r") as fin:
    lines = fin.readlines()
    target_found = False

    for line in reversed(lines):
        if not target_found:
            # 找到最后一个new(后,开启查找模式
            if 'new(' in line:
                target_found = True
        else:
            clean_line = line.strip()
            if clean_line and 'fourth' in clean_line:
                print(clean_line)
                break

关键说明

  • 用with语句管理文件,自动处理关闭,避免资源浪费。
  • 加入strip()和空行判断,跳过文件末尾的空行,确保匹配有效内容。
  • 两种方式都能精准定位到目标行,方式一逻辑更直观,方式二无需额外存储索引,内存占用更低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:40:41