【发布时间】:2019-11-29 17:56:05
【问题描述】:
这个函数获取一些tictactoe板并返回合法尝试的动作(-1代表“O”,1代表“X”,0代表空格)
def legal_locations(boards, moves):
legal_idxs, legal_locs = [], []
illegal_idxs, illegal_locs = [], []
for i, j in enumerate(moves):
# The middle index here is 0 because the locations > 0 are reserved for historical states.
# We only want to examine the current board state.
if boards[i][0][j]: # This location is occupied
illegal_idxs.append(i)
illegal_locs.append(j)
else: # unoccupied
legal_idxs.append(i)
legal_locs.append(j)
return (legal_idxs, legal_locs), (illegal_idxs, illegal_locs)
它工作正常,但“boards”只是一个矩形 numpy 数组,“moves”是一个列表。我认为必须有一种更快的方法来使用 numpy 完成此任务。有什么想法吗?
如果不能提高效率 - 很高兴知道这个问题是如何使其难以优化的。
编辑:
boards =
array([[[ 0, 1, 0, -1, 0, 0, 0, -1, 0],
[ 0, 1, 0, 0, 0, 0, 0, -1, 0],
[ 0, 0, 0, 0, 0, 0, 0, -1, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 1, -1, 0, 0, 0, -1],
[ 0, 0, 0, 1, -1, 0, 0, 0, 0],
[ 0, 0, 0, 0, -1, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0]]])
这个棋盘数组显示了两个游戏,每个游戏都有 4 个历史状态。
moves =
[2, 8]
这个移动数组显示两个索引。 因此,感兴趣的位置是:
boards[0][0][2]
boards[1][0][8]
所以在这个例子中,我们的 fxn 会得到以下回报:
([0], [2]), ([1], [8])
EDIT2:一个更核心的例子:
@AlexanderCécile 我想问题的一部分是我不知道如何使用列表作为索引。例如,我不知道如何减少这个循环......
for i in range(legal.shape[0]):
legal[i, 0, index_list[i]] = -1
其中 len(index_list) == len(legal)
如果我能做到这一点,那么其他一切都应该使用 np.nonzero 就位
【问题讨论】:
-
你能分享更多你的代码和一些测试数据吗?请参阅:minimal reproducible example。
-
我也很好奇为什么第二维用于“时间”,我本来希望用第一维代替。最后,
moves是如何组织的?你使用的是enumerate(),所以我不确定它的结构。 -
我同意@AlexanderCécile——这将有助于查看数据。通常,您真的不需要使用 NumPy 进行循环,几乎总有一种方法可以使用索引或类似方法来做您想做的事情——而且几乎总是更快。
-
您可以使用
numpy.nonzero(),一目了然。 -
刚刚看到你的编辑,明天试一试:)
标签: python numpy numpy-ndarray numpy-slicing