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

Python如何用enumerate遍历嵌套列表获取网格坐标并按要求输出

问题解决方法

核心错误原因

  • enumerate() 每次迭代返回的是 (索引值, 遍历元素) 的二元组,原代码没有对返回结果拆包,直接把元组当成下标使用导致取值异常
  • 调用check_square时传参逻辑完全错误,将enumerate对象直接传入方法,没有获取到实际的行列坐标值
  • 原输出格式没有匹配要求的单引号包裹参数的格式

修改后完整代码

ANIMALS = {
    "a": "alpaca",
    "k": "kangaroo",
    "@": "cat",
    "h": "hamster",
    "l": "leopard"
}


def check_square(char, row_num, col_num):
    if char != " ":
        # 调整输出格式匹配要求
        print("From square '{}', '{}' we find '{}'"
              .format(col_num, row_num, ANIMALS[char]))


def check_field(field):
    # 第一层遍历拿到行号+该行所有格子
    for row_idx, row_content in enumerate(field):
        # 第二层遍历拿到列号+当前格子的字符
        for col_idx, char in enumerate(row_content):
            # 按要求调用check_square方法
            check_square(char, row_idx, col_idx)


field = [
    [" ", "a", " ", " ", "l"],
    [" ", "k", "@", "k", " "],
    ["h", " ", "a", "k", " "]
]

check_field(field)

运行输出结果

From square '1', '0' we find 'alpaca'
From square '4', '0' we find 'leopard'
From square '1', '1' we find 'kangaroo'
From square '2', '1' we find 'cat'
From square '3', '1' we find 'kangaroo'
From square '0', '2' we find 'hamster'
From square '2', '2' we find 'alpaca'
From square '3', '2' we find 'kangaroo'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:54:03