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

Python中使用match-case匹配数组元素赋值时第4行报错求解决

解决match-case语法错误与函数优化方案

首要错误:缩进问题

你的代码里for i in range(r):未缩进,Python要求函数内部代码必须缩进,这是导致match行报错的直接原因。

其他潜在问题及修复

除缩进外,代码还有多处会引发异常的问题:

  • 函数未传入r、c、img、matrixColored等必要变量,直接使用会触发NameError
  • matrixColored未提前初始化,直接赋值索引会触发IndexError或NameError
  • match-case仅支持Python 3.10及以上版本,若使用旧版本会触发语法错误

修复后的完整代码

def colorPrint(r, c, img):
    # 初始化与img同尺寸的颜色矩阵
    matrixColored = [[None for _ in range(c)] for _ in range(r)]
    for i in range(r):
        for j in range(c):
            match img[i][j]:
                case 1:
                    matrixColored[i][j] = 'red'
                case 2:
                    matrixColored[i][j] = 'green'
                case 3:
                    matrixColored[i][j] = 'blue'
                case 4:
                    matrixColored[i][j] = 'yellow'
                case _:
                    return "something went wrong"
    return matrixColored

兼容旧Python版本的替代方案

如果你的Python版本低于3.10,无法使用match-case,可改用字典映射实现,兼容性更强:

def colorPrint(r, c, img):
    color_map = {1: 'red', 2: 'green', 3: 'blue', 4: 'yellow'}
    matrixColored = [[None for _ in range(c)] for _ in range(r)]
    for i in range(r):
        for j in range(c):
            val = img[i][j]
            if val not in color_map:
                return "something went wrong"
            matrixColored[i][j] = color_map[val]
    return matrixColored

内容的提问来源于stack exchange,提问作者The Code Whisperer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:01:16