我在运行构建完美迷宫的代码时遇到了这个错误。这是代码:
def walk(self, s, x, y):
neighboor = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
if s.size() == self.size**2: return
else:
while True:
new = choice(neighboor)
if self.is_valid(new[0], new[1]): break
while self.maze[new[0]][new[1]].getVisit():
if len(neighboor) != 0: new = choice(neighboor.remove(new))
else:
temp = s.pop(s)
self.walk(s, temp[0], temp[1])
#print(new)
self.maze[new[0]][new[1]].changeVisit()
if new == neighboor[1]:
self.maze[x][y].changeNorth()
self.maze[new[0]][new[1]].changeSouth()
elif new == neighboor[0]:
self.maze[x][y].changeSouth()
self.maze[new[0]][new[1]].changeNorth()
elif new == neighboor[2]:
self.maze[x][y].changeEast()
self.maze[new[0]][new[1]].changeWest()
elif new == neighboor[3]:
self.maze[x][y].changeWest()
self.maze[new[0]][new[1]].changeEast()
s.push(new)
self.walk(s, new[0], new[1])
这是我得到的错误:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a.search()
File "C:UsersSerenaDesktopXAprojectStack.py", line 93, in search
self.walk(s, startX, startY)
File "C:UsersSerenaDesktopXAprojectStack.py", line 76, in walk
self.walk(s, new[0], new[1])
File "C:UsersSerenaDesktopXAprojectStack.py", line 76, in walk
self.walk(s, new[0], new[1])
File "C:UsersSerenaDesktopXAprojectStack.py", line 76, in walk
self.walk(s, new[0], new[1])
File "C:UsersSerenaDesktopXAprojectStack.py", line 76, in walk
self.walk(s, new[0], new[1])
File "C:UsersSerenaDesktopXAprojectStack.py", line 76, in walk
self.walk(s, new[0], new[1])
File "C:UsersSerenaDesktopXAprojectStack.py", line 76, in walk
self.walk(s, new[0], new[1])
File "C:UsersSerenaDesktopXAprojectStack.py", line 52, in walk
if len(neighboor) != 0: new = choice(neighboor.remove(new))
File "C:Python34librandom.py", line 253, in choice
i = self._randbelow(len(seq))
TypeError: object of type 'NoneType' has no len()
我认为neighbor是一个包含四组数字的列表,它应该有len()。
我是编程新手,如有任何帮助,不胜感激。
几件事。首先,如果您使用的是从通配符导入(从随机导入*)导入的choice()之类的东西,那么包含它会很有用,因为否则我们只是猜测该函数是从哪里获得的。此外,通配符导入也被认为是不好的做法。
问题是列表的remove()方法返回None。不能从None中选择某些内容,因为None不是可迭代的。也就是说remove()方法不支持链接。尝试更改:
if len(neighboor) != 0: new = choice(neighboor.remove(new)) # Passes None to choice() which raises an error
至
if len(neighboor) != 0:
neighboor.remove(new) # removes the element from neighboor
new = choice(neighboor) # Chooses from the list as you intended
您可能还有其他错误,但这是您发布的回溯中的错误。
对于未来,我建议您熟悉Python的回溯,因为它会告诉您到底出了什么问题。这是一个资源。
顺便说一句,你指的是邻居而不是邻居吗?