列表中的对象不可迭代

时间:2018-10-01 08:13:16

标签: python oop iterable

我正在用Python创建国际象棋游戏。下面我有一种显示板的方法。问题是,它仅显示第一个square.piece.piece_type。我已经测试了列表的内容,总共有64个(应该是这样)。如何返回所有对象变量?

    def board_display(self):
    counter = 0
    while counter <= len(self.squares):
        for square in self.squares:
            return square.piece.piece_type
    counter += 1

我尝试使用counter作为索引,但是它返回TypeError: 'square' object is not iterable

编辑(已解决):

返回(显然它结束了整个函数,而不仅仅是循环)是主要问题。我将单独的列表部分放置在新列表中,并返回了该新列表。

    def board_display(self):
    output = []

    for square in self.squares:
        output.append(square.piece.piece_type)
    return output

1 个答案:

答案 0 :(得分:1)

问题中描述的问题是由于您一旦到达null就离开了return函数而引起的。此后不会执行,因此您仅返回第一个board_displaysquare.piece.piece_type 从不变为1或2等。

因此,您可能要返回正方形列表,而不是每个正方形。