在制作 Connect Four 游戏时,我在一个名为 的函数中遇到了一个奇怪的问题make_move,当两个等效的 return 语句表现不同时。唯一的直接依赖函数是put_piece(board, column, player),它将玩家的棋子放在棋盘给定列中最底部的空白位置。put_piece返回一个包含两个元素的元组:棋子结束的行的索引(如果列已满,则为 -1)和更新后的棋盘。该put_piece功能已正确实现。该make_move功能是在分歧发生。如果我使用通常的 if else 返回表示法实现,它会成功返回row(放置棋子的行的索引)和board(更新的板),如下所示:def make_move(board, max_rows, max_cols, col, player): """ Put player's piece in column COL of the board, if it is a valid move. Return a tuple of two values: 1. If the move is valid, make_move returns the index of the row the piece is placed in. Otherwise, it returns -1. 2. The updated board """ if 0 <= col < len(board[0]): return put_piece(board, max_rows, col, player) return -1, board这是make_move应该如何返回:>>> rows, columns = 2, 2>>> board = create_board(rows, columns)>>> row, board = make_move(board, rows, columns, 0, 'X')>>> row1>>> board[['-', '-'], ['X', '-']]但是,如果我更改make_move为def make_move(board, max_rows, max_cols, col, player): """ Put player's piece in column COL of the board, if it is a valid move. Return a tuple of two values: 1. If the move is valid, make_move returns the index of the row the piece is placed in. Otherwise, it returns -1. 2. The updated board """ return put_piece(board, max_rows, col, player) if 0 <= col < len(board[0]) else -1, board两个返回值都作为一个元组分配给row,并board简单地继承前一个值。>>> rows, columns = 2, 2>>> board = create_board(rows, columns)>>> row, board = make_move(board, rows, columns, 0, 'X')>>> row(1, [['-', '-'], ['X', '-']])>>> board[['-', '-'], ['-', '-']]除了符号之外,两种编写函数的方式在字面上是相同的。知道为什么会这样吗?
1 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
这是由于优先级。逗号的优先级相当低,所以
put_piece(board, max_rows, col, player) if 0 <= col < len(board[0]) else -1, board
相当于
((put_piece(board, max_rows, col, player) if 0 <= col < len(board[0]) else -1), board)
但你真的想要
put_piece(board, max_rows, col, player) if 0 <= col < len(board[0]) else (-1, board)
添加回答
举报
0/150
提交
取消