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

Python调用re.findall报list index out of range 脚本运行失败shell正常

问题根因

  • 最直接的报错原因是:re.findall()在没有匹配到结果时会返回空列表,你直接对返回结果取[0]索引就会触发IndexError: list index out of range。
  • 你的代码逻辑本身存在设计缺陷:每一行指令只会对应forward/up/down中的一种,你却并行写了3个独立的if判断,比如当前行是forward 6,执行到判断^u的re.findall('^u',a)[0]时必然匹配不到,直接触发报错。
  • 额外的隐患:你用split("\n")切割文件内容,如果文件末尾存在空行,切割出来的最后一个元素是空字符串,也会触发所有正则匹配失败的问题;另外你提取数字的正则\d只匹配单个数字,如果指令里的数值大于9(比如forward 15),只会提取到第一位数字,计算结果会出错。

修复方案

你可以直接用更简洁的逻辑改写代码,避免无效匹配:

import re

forward = 0
pos = 0

with open("day2.txt", "r") as file:
    # 逐行读取,自动跳过空行
    for line in file:
        line = line.strip()
        if not line:
            continue
        # 一次匹配提取指令类型和数值
        match = re.match(r'^(forward|up|down) (\d+)', line)
        if not match:
            # 遇到格式异常的行可以跳过也可以打印告警,按需调整
            continue
        cmd, num = match.groups()
        num = int(num)
        if cmd == 'forward':
            forward += num
        elif cmd == 'up':
            pos -= num
        elif cmd == 'down':
            pos += num

print(forward * pos)

如果你不想大改原有逻辑,也可以至少把三个独立if改成if-elif结构,并且判断匹配结果是否非空再取索引:

# 原有逻辑最小修改版
import re
with open("day2.txt", "r") as file: 
    lines = [l.strip() for l in file if l.strip()]
    forward=0
    pos=0
    for a in lines:
        print(a)
        f_match = re.findall('^f',a)
        if f_match and f_match[0] == 'f':
             forward=forward+int(re.findall('\d+',a)[0])
             continue
        u_match = re.findall('^u',a)
        if u_match and u_match[0] == 'u':
             pos=pos-int(re.findall('\d+',a)[0])
             continue
        d_match = re.findall('^d',a)
        if d_match and d_match[0] == 'd':
             pos=pos+int(re.findall('\d+',a)[0])
             continue
print(forward*pos)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:36:04