一行if-else返回语句的Python不同输出

一行if-else返回语句的Python不同输出,python,list,if-statement,return,tuples,Python,List,If Statement,Return,Tuples,在制作连接四的游戏时,我在一个名为make_move的函数中遇到了一个奇怪的问题,两个等价的返回语句的行为不同 唯一的直接依赖函数是put_-piece(棋盘、列、玩家),它将玩家的棋子放在棋盘给定列中最底部的空白位置put_piece返回两个元素组成的元组:该块最后所在行的索引(如果列已满,则为-1)和更新的板。put\u片功能正确执行 make_move功能是出现分歧的地方。如果我使用通常的if-else返回符号实现,它将成功返回行(工件所在行的索引)和板(更新板),如下所示: def ma

在制作连接四的游戏时,我在一个名为
make_move
的函数中遇到了一个奇怪的问题,两个等价的返回语句的行为不同

唯一的直接依赖函数是
put_-piece(棋盘、列、玩家)
,它将玩家的棋子放在棋盘给定列中最底部的空白位置
put_piece
返回两个元素组成的元组:该块最后所在行的索引(如果列已满,则为-1)和更新的板。
put\u片
功能正确执行

make_move
功能是出现分歧的地方。如果我使用通常的if-else返回符号实现,它将成功返回
(工件所在行的索引)和
(更新板),如下所示:

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
但是,如果我将
更改为

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

这两种编写函数的方法除了表示法外,在字面上是相同的。知道为什么会发生这种情况吗?

这是由于优先权。逗号的优先级相当低,所以

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)
如果为0,则放置棋子(棋盘、最大行数、列数、玩家)
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)