试图弄清楚这个并行分配是如何工作的。完整代码可见here . (原始 Github python 文件)。这是我遇到的问题:
def assign_move(square):
# Parallel Assignment
target, direction = max(
((neighbor, direction) for direction, neighbor in enumerate(game_map.neighbors(square))
if neighbor.owner != myID),
default = (None, None),
key = lambda t: t[0].production)
我会尽可能多地分解它,但我可能做错了什么。
target, direction = max(iterable, default, key)
我们是否将目标和方向分配给同一件事?我认为并行赋值类似于 x, y = 5, 6
现在,如果我们看一下 iterable
,它是这样的:
iterable = ((neighbor, direction) for direction, neighbor in enumerate(game_map.neighbors(square)) if neighbor.owner != myID)
我们如何在 for 循环之前有 (neighbor , direction)
?这里的 if
语句有什么作用?如果 neighbor.owner != myID
,我们是否不需要 if block 下面的任何东西来运行?
如果迭代器为空,我们将返回 None, None
如下所示?
default = (None, None),
这就是我们用来确定最大值的函数?
key = lambda t: t[0].production)
背景(如果需要): 这是要在游戏中玩的机器人的代码 Halite .它是在此 GitHub repo 中找到的预建机器人.
最佳答案
此处的max
函数返回(direction , neighbors)
相对于neighbor.production
的最大tuple
>(正如我们从 key
中理解的那样)如果 neighbor.owner != myID
发生并且迭代器为空 default,则允许邻居参与此迭代= (None, None)
将是 target
和 directions
值,所以 target
是 neighbor
大多数 production
都在最后。
关于Python 并行赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705136/