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

Python实现:仅打印后续紧跟'y行'的目标'x行'

解决仅打印后续紧跟'y'行的'x'行问题

输入文件内容

this is line x  
this is line y  
this is line x 
this is line x  
this is line x  
this is line y   
this is line x  
this is line x  
this is line y

需求说明

仅当this is line y出现在this is line x之后时,打印该this is line x(本示例应仅打印3次)。

尝试的代码(不符合需求)

skip_line = True  
with open("input_n.txt","r") as myfile:
     for line in myfile:
        if "x" in line:
            skip_line = False
        elif "y" in line:
            skip_line = True
        else:
            pass
        if skip_line:
            continue
        print(line)

这段代码会打印所有this is line x,无法满足“仅打印后面跟着'y'的'x'行”的要求。

修改后的代码方案

核心思路是检查每一行的下一行是否为'y'行,只有当前行是'x'且下一行是'y'时,才打印当前行:

with open("input_n.txt", "r") as myfile:
    # 读取所有行并去除换行符,方便后续处理
    lines = [line.rstrip('\n') for line in myfile]

# 遍历到倒数第二行,避免索引越界
for i in range(len(lines) - 1):
    current_line = lines[i]
    next_line = lines[i + 1]
    if "x" in current_line and "y" in next_line:
        print(current_line)

代码说明

  1. 先把文件所有行加载到列表中,这样可以方便地访问当前行的下一行内容。
  2. 遍历列表时只到倒数第二行,防止访问lines[i+1]时出现索引越界错误。
  3. 仅当当前行包含'x'且下一行包含'y'时,才打印当前的'x'行,正好匹配需求中的3次打印结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:24:31