3

所以下面的 Python 代码得到了错误: TypeError: 'NoneType' object has no attribute ' getitem '

我无法弄清楚为什么列表“路径1 ”没有被识别为列表,而是被识别为 NoneType。

我检查了以前的堆栈问题,谷歌搜索,所有这些,但我无法弄清楚为什么会这样。很接近(我认为),但我不知道为什么我的 state = path[-1] 调用会出现此错误。

有什么想法吗?非常感激。

谢谢

代码:

import re
import string



gr = {
    "A":["B","C","D"],
    "B":["A","E"],
    "C":["A","E"],
    "D":["A","H","I","J"],
    "E":["B","C","F","G","H"],
    "F":["E"],
    "G":["E","H"],
    "H":["D","E","G","K"],
    "I":["D","K","L"],
    "J":["D","M"],
    "K":["I","M","H"],
    "L":["I"],
    "M":["K","J"]
    }

def graphSearch(graph, start, dest):
    frontier = [[start]]
    explored = []
    options = []
    if frontier == []: return "I hope you enjoyed riding aboard the failboat"
    while len(frontier)>0:
        path = frontier.pop()
        state = path[-1]
        if state == dest: 
            return path
        else:
            for a in graph[state]:
                if a not in path:
                    newP = path.append(a)
                    frontier.append(newP)
    return options



print graphSearch(gr, "A", "M")
4

1 回答 1

5
newP = path.append(a)
frontier.append(newP)

append 不会返回任何内容(它会修改原始列表),因此您最终会将一堆附加None到您的列表中。

.pop()工作正常; 这state = path[1]是失败的,因为pop()弹出了None您在上一次迭代中附加的项目之一。

于 2013-01-23T04:52:25.230 回答