如何解决Python打印从列表弹出窗口返回,但是在访问时给出'NoneType'不可下标的错误
我正在使用以下代码从堆栈中插入和弹出:
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))返回:
<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 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
错误似乎很常见,但是我找不到与我在此遇到的问题类似的任何解释,因为据我所知,我并非像其他 Stackoverflow问题那样,不小心将某些列表方法分配给了变量。
解决方法
问题很可能来自
...
for succ in problem.getSuccessors(curr_path[-1]):
open_stack.push(curr_path.append(succ[0]))
list
的append方法将返回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
p.s。您也可以使用list as stack
编辑:轻微错误
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。