int'对象不是可迭代的,但我并未尝试迭代

1 投票
1 回答
2479 浏览
提问于 2025-04-16 16:06

下面这段代码试图创建一个地图,显示从地图上每个方格到指定位置所需的最小移动次数。整体来看,这个函数和问题关系不大,但我觉得有必要把我的问题放在上下文中说明。我还从collections模块导入了deque。奇怪的地方出现在第7行。我遇到了TypeError: 'int' object not iterable的错误。但根据我的理解,语句“distance_from_loc, f_loc = squares_to_check.popleft()”不应该尝试去迭代任何东西。任何帮助都将非常感激。

    def complex_distance(self, loc):
        row, col = loc
        squares_to_check = deque((0, loc))
        self.complex_distance_map = zeros((self.height, self.width), int) + 999
        self.complex_distance_map[row][col] = 0
        while squares_to_check:
            distance_from_loc, f_loc = squares_to_check.popleft()
            distance_from_loc += 1
            for d in AIM:
                n_loc = self.destination(f_loc, d)
                n_row, n_col = n_loc
                if distance_from_loc < self.complex_distance_map[n_row][n_col] and not self.map[n_row][n_col] == -4:
                    squares_to_check.append((distance_from_loc, n_loc))
                    self.complex_distance_map[n_row][n_col] = distance_from_loc

1 个回答

7

这一行代码确实是在尝试进行循环:

>>> a, b = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

这一行代码

squares_to_check = deque((0, loc))

是用两个元素 0loc 来初始化一个双端队列,而不是用一个单独的元素 (0, loc)。你可以使用

squares_to_check = deque([(0, loc)])

来获得想要的结果。

撰写回答