【问题标题】:indexing over list of locations in 2d array efficiently有效地索引二维数组中的位置列表
【发布时间】: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


【解决方案1】:

将数组转换为bool,然后使用np.where 生成与True 值对应的索引(~ 运算符将反转转换数组)。对于单板:

array = np.array([[1, 0, 0], [-1, 1, 0], [1, -1, -1]])
mask = array.astype(bool)
illegal_row, illegal_col = np.where(mask)
legal_row, legal_col = np.where(~mask)

这可以通过运行领先索引扩展到多个板。

【讨论】:

  • 来自numpy.where() docs:当只提供条件时,这个函数是np.asarray(condition).nonzero()的简写。应该首选直接使用非零值,因为它对子类的行为正确。 也不需要强制转换为 bool。
猜你喜欢
  • 2020-06-11
  • 1970-01-01
  • 2016-05-21
  • 2022-11-19
  • 2021-01-12
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
相关资源
最近更新 更多