[英].pop() seems to be triggering a TypeError in Python, even though the result should be a list
So the below Python code gets the error: TypeError: 'NoneType' object has no attribute ' getitem ' 所以下面的Python代码得到错误:TypeError:'NoneType'对象没有属性' getitem '
I can't figure out why the list 'path 1 ' doesn't get recognized as a list, but instead is recognized as NoneType. 我无法弄清楚为什么列表'路径1 '不会被识别为列表,而是被识别为NoneType。
I've checked previous Stack questions, googled, all of that, but I can't figure out why it is happening. 我已经检查了之前的Stack问题,谷歌搜索了所有这些,但我无法弄清楚它为什么会发生。 This came close-ish (I think) but I can't tell why my state = path[-1] call is turning up this error.
这是近距离的(我认为),但我不知道为什么我的state = path [-1]调用正在出现这个错误。
Any thoughts? 有什么想法吗? Much appreciated.
非常感激。
Thanks 谢谢
Code: 码:
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")
newP = path.append(a)
frontier.append(newP)
append doesn't return anything (it modifies the original list in place), so you wind up appending a bunch of None
to your list. append不会返回任何内容(它会修改原始列表),因此您最终会在列表中附加一堆
None
。
.pop()
works fine; .pop()
工作正常; it's the state = path[1]
that fails, because the pop()
popped off one of the None
items you appended in a previous iteration. 这是失败的
state = path[1]
,因为pop()
弹出了你在上一次迭代中附加的None
项之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.