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

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

[['-', '-'], ['-', '-']]

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


素胚勾勒不出你
浏览 131回答 1
1回答

桃花长相依

这是由于优先级。逗号的优先级相当低,所以put_piece(board,&nbsp;max_rows,&nbsp;col,&nbsp;player)&nbsp;if&nbsp;0&nbsp;<=&nbsp;col&nbsp;<&nbsp;len(board[0])&nbsp;else&nbsp;-1,&nbsp;board相当于((put_piece(board,&nbsp;max_rows,&nbsp;col,&nbsp;player)&nbsp;if&nbsp;0&nbsp;<=&nbsp;col&nbsp;<&nbsp;len(board[0])&nbsp;else&nbsp;-1),&nbsp;board)但你真的想要put_piece(board,&nbsp;max_rows,&nbsp;col,&nbsp;player)&nbsp;if&nbsp;0&nbsp;<=&nbsp;col&nbsp;<&nbsp;len(board[0])&nbsp;else&nbsp;(-1,&nbsp;board)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python