首页 > 解决方案 > 单行if else return语句的Python不同输出

问题描述

在制作 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')
>>> row
1
>>> 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
[['-', '-'], ['-', '-']]

除了符号之外,这两种编写函数的方式在字面上是相同的。知道为什么会这样吗?

标签: pythonlistif-statementreturntuples

解决方案


这是由于优先级。逗号的优先级很低,所以

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)

推荐阅读