Python:两个不相等的整数

时间:2019-03-22 03:49:10

标签: python

我正在制作一个Eller Maze生成程序,并且遇到了最奇怪的问题。我可以选择一个随机整数,并将其与迷宫中单个列的长度进行比较,因此程序知道如何处理查找邻居的过程。由于某种原因,它不会将两个整数识别为相等。我注意到这里的一个常见错误是它们是不同的类型,我通过将它们都转换为int积极地防止了这种情况。这是代码示例和一些调试输出:

choice = random.randint(0, len(self.unvisited)-1)
        if choice == 0 and (self.unvisited[0] == mastercol[0]):
            choice = self.unvisited[0]
            neighbor = mastercol[1]
            neighbordir = "south"
        elif int(choice) == int(len(mastercol)-1): #<<< THE IF STATEMENT IN QUESTION
            choice = self.unvisited[choice]
            neighbor = mastercol[choice-1]
            neighbordir = "north"
        # choose a random neighbor on the list.
        else:
            neighbors = [(-1, "south"),(1, "north")]
            neighbor = neighbors[random.randint(0,1)]
            neighbordir = neighbor[1]
            choice = self.unvisited[choice]
            print("choice=" , choice, "Len Mastercol -1 = ", len(mastercol)-1)
            neighbor = mastercol[choice + neighbor[0]]

调试输出:

    choice= 4 Len Mastercol -1 =  4
Traceback (most recent call last):
  File "C:\Users\User\Desktop\Game Stuff\Mazes\MazeGen.py", line 292, in <module>
    NewApp.Run()
  File "C:\Users\User\Desktop\Game Stuff\Mazes\MazeGen.py", line 271, in Run
    self.Grid = self.Maze.MazeStep()
  File "C:\Users\User\Desktop\Game Stuff\Mazes\MazeGen.py", line 187, in MazeStep
    neighbor = mastercol[choice + neighbor[0]]
IndexError: list index out of range

因此,在调试输出中,我可以看到我们正走向灾难,但是那些相等的值应该已经在上面的省略号中捕获了,对吗?

知道我在这里缺少什么吗?

编辑:

  

您正在打印语句之前修改选择。 – 6分钟前Selcuk

是的,就是问题所在。我正在改变价值。我需要先选择邻居单元格,然后再更改选择变量。谢谢塞尔柱克!这样就解决了。

0 个答案:

没有答案