无法更新嵌套lis中的值

2024-09-27 07:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个班级项目写一个tic tac脚趾游戏。基本上我有这个清单:

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

我只想根据玩家的不同,用X或O更新列表值。我试图使用以下函数来实现,其中p是从用户输入的整数(是的,我确保输入实际上是整数而不是字符串):

^{pr2}$

当我运行此代码时,我会发现一个错误,即列表索引必须是整数而不是列表类型。或者,我尝试用这行替换变量c,而不是^{{cd1>}

^{pr3}$

打印c的值和类型,显示c为int,并与用户输入的值匹配。所以我可以找到变量,类型匹配,我只是无法更新原始列表中的值。我是否错误地使用全局变量?我搞不懂为什么它不会更新。以下是迄今为止的整个计划:

^{pr4}$

Tags: 项目函数字符串用户游戏类型列表错误
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:29

循环中的r和{}是行和列,而不是它们的索引。您需要跟踪索引以更新值。您可以使用enumerate function执行此操作。在

def place_sym(p):
    global turn
    global grid
    global plyr

    # row_index will be 0, 1 or 2 (the position in grid).
    # row is an array of 3 integers.
    for row_index, row in enumerate(grid):
        # column_index will be 0, 1, 2 (the position in the row)
        # column_value is the actual integer value to check against
        for column_index, column_value in enumerate(row):
            if column_value == p:
                grid[row_index][column_index] = plyr[turn]

相关问题 更多 >

    热门问题