TypeError:' int'对象不可迭代... 2D数组

时间:2016-12-27 19:07:11

标签: python multidimensional-array typeerror iterable

我试图设置多维数组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

1 个答案:

答案 0 :(得分:0)

我不确定代码的其余部分是什么样的,但在 line:133 self.grid[(x, y)].set_cell(value, secondary)上,它看起来不像元组(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)
        # 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