亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

單行的 Python 不同輸出 if else return 語句

單行的 Python 不同輸出 if else return 語句

素胚勾勒不出你 2021-06-10 18:40:01
在制作 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)


查看完整回答
反對 回復 2021-06-22
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號