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

Python列表报错‘NoneType object is not subscriptable’的解决求助

网格路径规划项目:NoneType下标访问错误解决

问题描述

我正在做一个网格路径规划的个人项目,目标是生成从起点到终点的最短路径,同时避开不可通行的坐标点。目前遇到报错:'NoneType' object is not subscriptable,具体问题如下:

当用以下代码获取用户输入的不可通行点坐标时:

k = int(input("请输入不可通行点的数量: ")) # 原代码为斯洛伐克语,已转中文注释

if k >= 1:
    for i in range(k):
        cords_p = []
        cords_p = cords_p.extend([int(element_c) for element_c in input("请输入坐标点: ").split()]) # 问题核心行
else:
    print(cords_p)


x = cords[0]
y = cords[1]
print(x," ",y)

不用extend()的话,列表会被每次输入覆盖;但用了extend()后,cords_p变成了NoneType,后续路径判断代码里通过下标访问时直接报错。我是高中进阶初学者,希望得到解决帮助。

后续路径判断代码片段:

while cords[0] != cord_end[0] and cords[1] != cords_p[1]:
    while cords[1] != cord_end[1]:
        if cords[0] != cords_p[0]:
            if cords[0] <= cord_end[0] and cords[0] != cords_p[0]:
                cords[0] = cords[0]+1
                x = x+1
                print(x," ",y)
                continue
            elif cords[0] == cords_p[0] and cords[1] != cords_p[1]:
                cords[0] = cords[0]+1
                print(x," ",y)
                continue
        elif cords[1] == cords_p[1]:
            cords[0] = cords[0]+1
            print(x," ",y)
            continue
        break
    while cords[0] != cord_end[0]:   
        if cords[1] != cords_p[1]:        
            if cords[1] <= cord_end[1] and cords[1] != cords_p[1]:
                cords[1] = cords[1]+1
                y = y+1
                print(x," ",y)
                continue
            elif cords[1] == cords_p[1] and cords[0] != cords_p[0]:
                cords[1] = cords[1]+1
                print(x," ",y)
                continue
        elif cords[0] == cords_p[0]:
            cords[1] = cords[1]+1
            print(x," ",y)
            continue
        break     
print(cords)

错误原因与解决办法

核心错误点

list.extend()是原地修改列表的方法——它直接在原列表里添加元素,不会返回新列表,而是返回None。你把cords_p赋值为extend()的返回值,自然就变成了NoneType,后续用下标访问肯定报错。

另外代码还有两个小问题:

  1. cords_p = []放在循环内部,每次循环都会重置列表,就算不用extend也存不住多个坐标
  2. else分支里cords_p还没定义就打印,会触发NameError

修正后的输入处理代码

k = int(input("请输入不可通行点的数量: ")) 
cords_p = []  # 把列表初始化放在循环外面,避免每次重置

if k >= 1:
    for i in range(k):
        # 把输入的坐标转成整数列表,直接添加到cords_p中
        coords = list(map(int, input("请输入坐标点: ").split()))
        cords_p.append(coords)
else:
    print("没有不可通行点")

# 假设cords是已定义的起点坐标列表
x = cords[0]
y = cords[1]
print(x," ",y)

后续路径判断的优化提示

你当前的路径判断逻辑默认cords_p是单个坐标,但如果有多个不可通行点,需要遍历所有点做判断。比如每次移动前,检查下一步坐标是否在不可通行列表里:

# 示例:检查向右移动一步是否可行
next_x = cords[0] + 1
next_y = cords[1]
# 判断下一步不在不可通行点列表里才能移动
if [next_x, next_y] not in cords_p:
    cords[0] = next_x
    x = next_x
    print(x," ",y)

内容的提问来源于stack exchange,提问作者Peter Sládek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:55:21