Python的单行if else return语句的不同输出

时间:2018-09-20 23:49:12

标签: python list if-statement return tuples

在玩四连环游戏时,当两个等效的return语句的行为不同时,我在一个名为make_move的函数中遇到一个奇怪的问题。

唯一的直接依赖项功能是put_piece(board, column, player),该功能将玩家的棋子放在棋盘给定列的最底部空白处。 put_piece返回一个由两个元素组成的元组:片段结尾的行的索引(如果列已满,则为-1)和更新的木板。 put_piece函数已正确实现。

发生分歧的地方是make_move函数。如果我使用通常的if否则返回符号来实现,它将成功返回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
[['-', '-'], ['-', '-']]

除了记号外,编写函数的两种方式实际上是相同的。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

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

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)