python - 单行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
[['-', '-'], ['-', '-']]
除了符号之外,这两种编写函数的方式在字面上是相同的。知道为什么会这样吗?
解决方案
这是由于优先级。逗号的优先级很低,所以
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)
推荐阅读
- sails.js - 如何使机器退出响应返回 JSON?
- r - 我想使用 for 循环在我的 R 数据框中添加多个列
- omnet++ - OMNET++:如何在我的自定义继承模块中替换 INET 4.0 子模块?
- java - 了解优先队列中的 SORT 方法
- docker - 挂载操作系统特定的卷
- reactjs - 可以在呈现页面之前更改特定链接/页面/路径的元数据/图像/标题吗?
- react-native - Expo 构建错误不是描述性的 - 构建 JavaScript 包失败
- javascript - 如何在 Javascript 的一个文本框中添加两个数字?
- gradle - Gradle 插件 - getArtifacts() 导致“无法解析配置的所有依赖项...”
- python - Flask-WTF SelectMultipleField 填充数据库 ID 而不是名称