'int' 对象在使用枚举时没有属性“__getitem__”?

'int' object has no attribute '__getitem__' when using enumerate?

我正在尝试制作一个井字游戏,问题是检查 table 然后用所选索引处的玩家“0”或 'X' 更新它的函数.

请告诉我如何解决这个问题,因为我看不出这有什么问题。

table = [['1','2','3'],
         ['4','5','6'],
         ['7','8','9']]

def title():
    for row in table:
        print row

def check(indx, sym):
    for indd, row in enumerate(table):
        for ind, cell in enumerate(row):
            if cell == indx and cell != '0' or cell != 'X':
                table[indd][ind] = sym
            else:
                return False

def main():

    moves_left = 1
    while moves_left > 0:
        if moves_left == 1:
            title()
            indx = raw_input('Where do you want your nought?: ')
            new_table = check(indx, '0')
            if new_table != False:
                moves_left += 1
            else:
                print 'Invalid selection'
        elif moves_left == 2:
            title()
            indx = raw_input('Where do you want your cross?: ')
            new_table = check(indx, 'X')
            if new_table != False:
                moves_left -= 1
            else:
                print 'Invalid Selection'
        else:
            print 'it\'s a draw'

if __name__=='__main__':
    main()

我的回溯:

Traceback (most recent call last):
  File "tictac.py", line 45, in <module>
    main()
  File "tictac.py", line 28, in main
    new_table = check(indx, '0')
  File "tictac.py", line 19, in check
    table[indd[ind]] = sym
TypeError: 'int' object has no attribute '__getitem__'

改变

table[indd[ind]] = sym # you're treating an integer like a list, which is wrong

table[indd][ind] = sym

以便访问第“indd'th row & 'ind 列的单元格。

实际上,table[indd[ind]] 是这样做的简写:

table.__getitem__(indd.__getitem__(ind))

& 整数没有 getitem() 特殊方法。

DeveloperXY 已经解决了您的紧迫问题。还有几个。目前让你烦恼的是你的if逻辑不正确:

if cell == indx and cell != '0' or cell != 'X':

要么使用括号,要么学习布尔运算符的求值顺序。除其他事项外,此语句必须 始终 在开始时出现 True:每个单元格都不是 'X'。由于您对循环中的 每个 单元格执行更新,因此您将它们 all 更改为“0”。

相反,您需要设计逻辑来找到您想要更改的一个单元格(在单元格 == indx),然后仅更改那个 one 单元格。初学者试试这个:

def check(indx, sym):
    for indd, row in enumerate(table):
        for ind, cell in enumerate(row):
            if cell == indx:
                table[indd][ind] = sym
print table  # I added this to watch what happens to the actual game state.

请注意,我删除了 return 值:您 returning NoneFalse ,在语句if new_table中作用相同。 顺便说一句,请注意,如果您从 check return True,那么 moves_left变成2,你的主程序进入死循环。

现在,请注意,您的 title 函数根本不关注游戏状态:除了初始编号外,它不会打印任何内容。

这是否让您走得足够远以解决此问题?