【问题标题】:TypeError: 'int' object is not iterable...2D arrayTypeError:'int'对象不可迭代...二维数组
【发布时间】:2017-05-12 01:44:33
【问题描述】:

我正在尝试设置多维数组 Board.grid 中包含的单元格的类属性。我收到以下错误消息:

  File "newbs1.py", line 133, in get_and_set_board_item
    self.grid[x, y].set_cell(value, secondary)
  File "newbs1.py", line 129, in __getitem__
    return self.grid[x][y]
  File "newbs1.py", line 128, in __getitem__
    x, y = tup
  TypeError: 'int' object is not iterable

让 x 和 y 输入它们是如何来自其他人的帖子的想法,它解决了他们的问题,但它对我没有用。

class Board(object):
    def __init__(self):
        self.grid = []
        self.width = 10
        self.height = 10

    def __getitem__(self, tup):
        x, y = tup
        return self.grid[x][y]

    def get_and_set_board_item(self, x, y, value, secondary):
        print (x, y, value, secondary)
        self.grid[(x, y)].set_cell(value, secondary)


class Cell():
    def __init__(self):
        self.is_ship = False
        self.is_hidden = False
        self.ship_symbol = ""

    def set_cell(self, value, secondary):
        if secondary == None:
            self.is_hidden = value
        else:
            self.is_ship = value
            self.ship_symbol = secondary

【问题讨论】:

    标签: python multidimensional-array typeerror iterable


    【解决方案1】:

    我不确定您的其余代码看起来如何,但在 line:133self.grid[(x, y)].set_cell(value, secondary) 上,元组 (x, y) 看起来不像是 Cell 输入。

    也许可以试试:

    class Board(object):
        def __init__(self):
            self.grid = []
            self.width = 10
            self.height = 10
    
        def __getitem__(self, tup):
            x, y = tup
            return self.grid[x][y]
    
        def get_and_set_board_item(self, x, y, value, secondary):
            print (x, y, value, secondary)
            # add this line #
            self.grid[x][y] = Cell() # set this to a cell type
            # ************* #
            self.grid[x][y].set_cell(value, secondary)
    
    
    class Cell():
        def __init__(self):
            self.is_ship = False
            self.is_hidden = False
            self.ship_symbol = ""
    
        def set_cell(self, value, secondary):
            if secondary == None:
                self.is_hidden = value
            else:
                self.is_ship = value
                self.ship_symbol = secondary
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2023-01-22
      • 2020-10-14
      • 2018-09-29
      • 2020-02-26
      • 2015-04-06
      相关资源
      最近更新 更多