【问题标题】:Python different output for one-line if else return statement单行if else return语句的Python不同输出
【发布时间】:2019-02-25 08:00:43
【问题描述】:

在制作 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

两个返回值都作为一个元组分配给rowboard 只是继承前一个值。

>>> rows, columns = 2, 2
>>> board = create_board(rows, columns)
>>> row, board = make_move(board, rows, columns, 0, 'X')
>>> row
(1, [['-', '-'], ['X', '-']])
>>> board
[['-', '-'], ['-', '-']]

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

【问题讨论】:

    标签: python list if-statement return tuples


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2017-02-05
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 2017-07-03
      • 2018-01-30
      相关资源
      最近更新 更多