python - 为什么我的函数不更新由嵌套列表组成的全局变量?(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)
输出:
- - -
- - -
- - -
[['','',''],['','',''],['','','']]
解决方案
分配给变量不会修改最初复制变量值的列表元素。您需要分配给列表元素本身。更改第二个循环,以便获得列表索引,然后您可以分配给该元素。
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()
推荐阅读
- php - 带有 CURLFile 的 CURL 适用于 PHP7.3 但不适用于 PHP7.4
- java - 如何创建密码以防止用户发现密码并在桌面应用程序 gui 中更改密码
- html - CSS:更改特定列中文本的颜色-但不在该列标题上?
- java - eXistDB 在 5.2.0 版本中没有 httpclient?
- sql - 查找重复预订
- php - 如何在我的 ForEach 循环中获取 Category + 子项
- java - 在 Java 中生成文本文件时应该使用“\r\n”还是“\n”?
- c# - RegistryKey 更改为新的 csproj 格式
- json - 来自 txt 文件的 Grep(JSON 格式)
- nginx - 无法从对等 v-net 连接到专用 v-net 上的 AKS 内部入口