首页 > 解决方案 > 为什么我的函数不更新由嵌套列表组成的全局变量?(python)

问题描述

我正在创建一个函数来显示变量board。函数 display_board 的 else 部分应该将board的元素更改为“-”。第一个 if 语句用于我的程序的另一个变量,称为位置,它工作正常。当我调用 display_board 时,它输出正确的格式,但实际上并没有改变board,正如它在打印board时所看到的那样。任何想法为什么它不起作用?

旁注:这是针对 python 中的介绍性编程课程,因此,嵌套列表与我的知识/课程范围一样先进。

board = [

[' ', ' ', ' '],

[' ', ' ', ' '],

[' ', ' ', ' ']

]

def display_board(board):
    if board == locations:
        for row in locations:
            for column in row:
                print(column, end=' ')
        print()
# This chunk below is the important code that is not altering *board*
    else:
        for row in board:
            for column in row:
                if column == 'X':
                    print(column, end=' ')
                elif column == 'O':
                    print(column, end=' ')
                else:
                    column = '-'
                    print(column, end=' ')
            print()
display_board(board)
print(board)

输出:

- - - 
- - - 
- - - 

[['','',''],['','',''],['','','']]

标签: pythonfunctionglobal-variablestic-tac-toe

解决方案


分配给变量不会修改最初复制变量值的列表元素。您需要分配给列表元素本身。更改第二个循环,以便获得列表索引,然后您可以分配给该元素。

    for row in board:
        for index, column in enumerate(row):
            if column == 'X':
                print(column, end=' ')
            elif column == 'O':
                print(column, end=' ')
            else:
                row[index] = '-'
                print(row[index], end=' ')
        print()

推荐阅读