我正在使用 2-d Numpy 数组制作井字游戏,并希望它能够使用字典将用户输入的输入转换为正确的矩阵位置,但出现此错误:< /p>
movesDict = {1:[[0][0]], 2:[[0][1]], 3:[[0][2]], 4:[[1][0]], 5:[[1][1]], 6:[[1][2]], 7:[[2][0]], 8:[[2][1]], 9:[[2][2]]}
IndexError: list index out of range
示例用户给出数字 1,它被转换为矩阵位置 [0][0],然后轮到他们放置
move = input("Move to which place {}?".format(turn))
realMove = movesDict[move]
答案 0 :(得分:1)
字典中的键是整数,用户输入的是字符串。
您需要将用户输入转换为整数,并且您可能需要检查无效输入。
move = input("Move to which place {}?".format(turn))
realMove = movesDict.get(int(move), 'Invalid Move')
答案 1 :(得分:0)
好吧,我意识到问题是我忘记在字典中的元素之间放置逗号。正确的代码是:
movesDict = {1:[[0],[0]], 2:[[0],[1]], 3:[[0],[2]], 4:[[1],[0]], 5:[[1],[1]], 6:[[1],[2]], 7:[[2],[0]], 8:[[2],[1]], 9:[[2],[2]]}