【问题标题】:Why is my function not updating a global variable consisting of nested lists?(python)为什么我的函数不更新由嵌套列表组成的全局变量?(python)
【发布时间】:2018-11-21 21:55:14
【问题描述】:

我正在创建一个函数来显示变量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)

输出:

- - - 
- - - 
- - - 

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

【问题讨论】:

    标签: python function global-variables tic-tac-toe


    【解决方案1】:

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

        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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 2020-02-01
      • 1970-01-01
      • 2019-04-01
      • 2011-12-08
      相关资源
      最近更新 更多