我正在尝试在python中编写迷宫生成器:迷宫由2D整数列表组成:列表用于表示此迷宫在我的世界中的样子,因此每个单元实际上都位于x的两个位置和y坐标是奇数。
我编写的用于修改“Maze”类中单元格值的方法不断抛出ValueError: list.remove(x): x not in list
异常。这是代码:
def setCell(self, x, y, request):
query = Maze.blocks[(2*x)+1][(2*y)+1]
if 0 <= x < (Maze.length-1)/2 and 0 <= y < (Maze.height-1)/2:
if request > query:
Maze.blocks[(2*x)+1][(2*y)+1] = request
print('changed cell ' + str(x) + ', ' + str(y) + ' to ' + str(request))
P = Point(x, y)
if request == Maze.WORKING: #WORKING and DONE are constants
Maze.List.append(P)
print(Maze.List) #debugging purposes
elif request == Maze.DONE:
print('trying to remove ' + str(P))
Maze.List.remove(Point(P.x, P.y))
#^^^here is the error.
#I tried to use Maze.List.remove(P),
#but that threw the exact same error.
print(Maze.List)
else:
print('should NOT be writing ' + str(request) + ' to ' + str(query) + '!')
return True
else:
print(str(request) + ' cannot overwrite ' + str(query))
return False
else:
print('invalid range for cell. req was ' + str(x) + ', ' + str(y))
return False
这是我运行代码的时候(我有方法打印出迷宫在添加每个点之后的样子:
changed cell 2, 7 to 1
[Point(0, 8), Point(0, 7), Point(0, 9), Point(1, 9), Point(1, 7), Point(2,7)]
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ * @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ * @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ * @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ * @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ * @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ * @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ * @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ : : : : : @ * @ * @ * @ * @ * @ * @ * $
$ : $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ : @ * @ * @ * @ * @ * @ * @ * @ * @ * $
$ : $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $ @ $
$ : : : @ * @ * @ * @ * @ * @ * @ * @ * $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
changed cell 0, 7 to 2
trying to remove (0, 7)
Traceback (most recent call last):
File "/Users/jim/PycharmProjects/MC_Maze/Maze.py", line 400, in <module>
if not M.setCell(A.x, A.y, Maze.DONE):
File "/Users/jim/PycharmProjects/MC_Maze/Maze.py", line 104, in setCell
Maze.List.remove(Point(P.x, P.y))
ValueError: list.remove(x): x not in list
你可以从列表中看到Point(0,7)在列表中,但是python似乎不同意。作为像python这样的低级语言的新手,我不知道为什么这不起作用。提前谢谢!
答案 0 :(得分:3)