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

Python二维网格路径标记程序报错求助:类型错误问题排查

解决路径标记程序中的变量冲突与逻辑错误

错误原因分析

你遇到的TypeError: can only concatenate list (not "int") to list是变量名冲突导致的:
在打印网格的循环中,你使用了for y in table:,这里的循环变量y会直接覆盖之前定义的坐标变量y = 0。第一次执行完打印循环后,y的值变成了table中的最后一个列表元素,再次执行y = y+1时,就会尝试把列表和整数相加,触发类型错误。

除此之外,你的代码还存在两个逻辑问题:

  • left和up方向没有修改坐标,只是重复标记当前位置,无法实现移动
  • 没有边界判断,输入超出网格范围的指令会导致索引越界错误

修正后的代码

table = []
line = input('Grid size: ')
grid_size = int(line)

# 初始化网格
for i in range(grid_size):
    row = []
    for j in range(grid_size):
        row.append('.')
    table.append(row)
table[0][0] = 'x'

# 打印初始网格
for row in table:
    print(''.join(row))

x, y = 0, 0
direction = input('Direction: ')
while direction.strip():  # 兼容空输入或仅空格的情况
    direction = direction.lower()
    valid_move = True
    
    # 处理方向移动,同时检查边界
    if direction == 'right':
        y += 1 if y + 1 < grid_size else 0
        valid_move = y < grid_size
    elif direction == 'left':
        y -= 1 if y - 1 >= 0 else 0
        valid_move = y >= 0
    elif direction == 'up':
        x -= 1 if x - 1 >= 0 else 0
        valid_move = x >= 0
    elif direction == 'down':
        x += 1 if x + 1 < grid_size else 0
        valid_move = x < grid_size
    else:
        print("无效指令,请输入左/右/上/下")
        valid_move = False
    
    # 更新并打印网格(仅当移动有效时)
    if valid_move:
        table[x][y] = 'x'
        for row in table:
            print(''.join(row))
    else:
        print("无法移动:超出网格边界")
    
    direction = input('Direction: ')

关键修改说明

  1. 修复变量冲突:将打印网格的循环变量从y改为row,避免覆盖坐标变量
  2. 补全移动逻辑:完善left和up方向的坐标修改逻辑,实现真正的移动
  3. 添加边界检查:判断移动后坐标是否在网格范围内,防止索引越界
  4. 优化输入处理:用direction.strip()判断空输入,兼容用户输入空格的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:10:03