在制作 Connect Four 游戲時,我在一個名為 的函數(shù)中遇到了一個奇怪的問題make_move,當(dāng)兩個等效的 return 語句表現(xiàn)不同時。唯一的直接依賴函數(shù)是put_piece(board, column, player),它將玩家的棋子放在棋盤給定列中最底部的空白位置。put_piece返回一個包含兩個元素的元組:棋子結(jié)束的行的索引(如果列已滿,則為 -1)和更新后的棋盤。該put_piece功能已正確實(shí)現(xiàn)。該make_move功能是在分歧發(fā)生。如果我使用通常的 if else 返回表示法實(shí)現(xiàn),它會成功返回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應(yīng)該如何返回:>>> 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[['-', '-'], ['-', '-']]除了符號之外,兩種編寫函數(shù)的方式在字面上是相同的。知道為什么會這樣嗎?
1 回答

桃花長相依
TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個贊
這是由于優(yōu)先級。逗號的優(yōu)先級相當(dāng)?shù)?,所?/p>
put_piece(board, max_rows, col, player) if 0 <= col < len(board[0]) else -1, board
相當(dāng)于
((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)
添加回答
舉報(bào)
0/150
提交
取消