Python 从 list pop 打印 return 但访问时出现 'NoneType' not subscriptable 错误

Python prints return from list pop but when accessing gives 'NoneType' not subscriptable error

我在以下代码中插入和弹出堆栈:

open_stack = util.Stack()

start = []
start.append(problem.getStartState())
open_stack.push(start)

while not open_stack.isEmpty():
    curr_path = open_stack.pop()
    print(type(curr_path))
    if problem.isGoalState(curr_path[-1]):
        return curr_path
    for succ in problem.getSuccessors(curr_path[-1]):
        open_stack.push(curr_path.append(succ[0]))
return False

打印(类型(curr_path)) returns:

<class 'list'>
<class 'NoneType'>

我得到的错误如下:

File "/home/ljagodz/uoft/search/search.py", line 101, in depthFirstSearch
if problem.isGoalState(curr_path[-1]):
TypeError: 'NoneType' object is not subscriptable

我使用的 Stack class 定义如下:

class Stack:
    "A container with a last-in-first-out (LIFO) queuing policy."

    def __init__(self):
        self.list = []

    def push(self, item):
        "Push 'item' onto the stack"
        self.list.append(item)

    def pop(self):
        "Pop the most recently pushed item from the stack"
        return self.list.pop()

    def isEmpty(self):
        "Returns true if the stack is empty"
        return len(self.list) == 0

我不明白为什么打印会这样,为什么我会收到这个错误。NoneType 错误似乎很常见,但我找不到与我在这里遇到的问题类似的任何解释,据我所知,我并没有像在提出此问题的其他 Whosebug 问题 中那样不小心将某些列表方法分配给变量。

问题最有可能来自

...
for succ in problem.getSuccessors(curr_path[-1]):
    open_stack.push(curr_path.append(succ[0]))

list 的附加方法将 return None 对象,而不是对结果列表的引用。即

print(curr_path.append(succ[0])) 

将打印 None。因此,您将 None 附加到堆栈中。尝试:

for succ in problem.getSuccessors(curr_path[-1]):
    open_stack.push(curr_path + [succ[0]]) #use listcomp

另见List Comprehensions

p.s。你也可以使用 list as stack

编辑:小错误