![](/img/trans.png)
[英]global keyword defined inside of a function is not updating my variable, but why?
[英]Why is my function not updating a global variable consisting of nested lists?(python)
我正在创建一个功能来显示可变板 。 函数display_board的else部分应该将board的元素更改为“-”。 第一个if语句用于我程序中另一个称为location的变量,它可以正常工作。 当我调用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)
输出:
- - -
- - -
- - -
[[',',','],[',',','],[',',',']]
分配给变量不会修改最初从中复制变量值的列表元素。 您需要分配给列表元素本身。 更改第二个循环,以便获得列表索引,然后可以分配给该元素。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.