Python 遍历数组时遇到问题,请告知
这是我尝试创建的一个函数,它读取用户移动并在数组中相应地调整它。我知道有些事情很简单,但我找不到Python 遍历数组时遇到问题,请告知,python,Python,这是我尝试创建的一个函数,它读取用户移动并在数组中相应地调整它。我知道有些事情很简单,但我找不到 def EnterMove(board): # # the function accepts the board current status, asks the user about their move, # checks the input and updates the board according to the user's decision # move = int(inpu
def EnterMove(board):
#
# the function accepts the board current status, asks the user about their move,
# checks the input and updates the board according to the user's decision
#
move = int(input("What space would you like to claim? "))
for row in board:
for column in row:
if move == column:
column = "O"
return board
board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
EnterMove(board)
print(board)
分配给
列
不会更改列表的内容。您需要获取索引并分配它。您可以使用enumerate()
获取索引和值
for row in board:
for i, column in enumerate(row):
if move == column:
row[i] = "O"
我想我理解你想要达到的目标。我调试了代码并做了一些更改。我意识到这是一个基本的解决方案,但我认为它很容易阅读和跟踪。我不确定这是否是你正在寻找的,但我希望它能有所帮助 如果其他任何人遇到类似问题并需要帮助,以下是一个应该可以使用的程序:
def EnterMove(board):
#
# the function accepts the board current status, asks the user about their move,
# checks the input and updates the board according to the user's decision
#
move = int(input("What space would you like to claim? "))
row = 0
while(row<len(board)):
col = 0
while(col<len(board[0])):
if move == 1+row*3+col:
board[row][col] = "0"
col+=1
row+=1
return board
board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
board = EnterMove(board)
print(board)
def EnterMove(板):
#
#该函数接受电路板当前状态,询问用户的移动情况,
#检查输入并根据用户的决定更新电路板
#
move=int(输入(“您想要申请什么空间?”)
行=0
while(row)您尚未说明问题所在,但重新指定列对正在迭代的数组没有影响。如果要修改数组,您需要迭代数组的索引,并执行board[i][j]=“O”
或类似操作。board[row][column]='O'
术语说明:您使用的是列表对象,而不是数组对象。@Julien这不起作用。行
和列
不是索引。是的,回答得太快了。。。