列表中的对象不可迭代
Object in list is not iterable
我正在 Python 创建一个国际象棋游戏。下面我有一个显示板的方法。问题是,它只显示第一个 square.piece.piece_type。我已经测试了列表的内容,有 64 个(应该是这样)。我怎样才能 return 所有对象变量?
def board_display(self):
counter = 0
while counter <= len(self.squares):
for square in self.squares:
return square.piece.piece_type
counter += 1
我试过使用计数器作为索引,但后来它 returns TypeError: 'square' object is not iterable
编辑(已解决):
return(显然它结束了整个函数而不仅仅是循环)是主要问题。我将单独的列表部分放在一个新列表中并 return编辑了那个新列表。
def board_display(self):
output = []
for square in self.squares:
output.append(square.piece.piece_type)
return output
您在问题中描述的问题是由于您一到达 return
就离开了 board_display
功能。之后它不会执行,因此您只 return 第一个 square.piece.piece_type
。 counter
从不 变成 1 或 2 等
因此您可能想要 return 方块列表而不是每个方块。
我正在 Python 创建一个国际象棋游戏。下面我有一个显示板的方法。问题是,它只显示第一个 square.piece.piece_type。我已经测试了列表的内容,有 64 个(应该是这样)。我怎样才能 return 所有对象变量?
def board_display(self):
counter = 0
while counter <= len(self.squares):
for square in self.squares:
return square.piece.piece_type
counter += 1
我试过使用计数器作为索引,但后来它 returns TypeError: 'square' object is not iterable
编辑(已解决):
return(显然它结束了整个函数而不仅仅是循环)是主要问题。我将单独的列表部分放在一个新列表中并 return编辑了那个新列表。
def board_display(self):
output = []
for square in self.squares:
output.append(square.piece.piece_type)
return output
您在问题中描述的问题是由于您一到达 return
就离开了 board_display
功能。之后它不会执行,因此您只 return 第一个 square.piece.piece_type
。 counter
从不 变成 1 或 2 等
因此您可能想要 return 方块列表而不是每个方块。