如何获取np.where以仅返回for循环所在的位置?(Python)
我已经创建了一个虚拟棋盘,其中有64个空格组成一个嵌套数组。我试着通过每个点,检查点的值是否为零。我使用np.where来获取spot的索引,但是最终np.where开始返回多个值,这会抛出一个错误。我如何让它只返回我当前所在地点的索引如何获取np.where以仅返回for循环所在的位置?(Python),python,numpy,Python,Numpy,我已经创建了一个虚拟棋盘,其中有64个空格组成一个嵌套数组。我试着通过每个点,检查点的值是否为零。我使用np.where来获取spot的索引,但是最终np.where开始返回多个值,这会抛出一个错误。我如何让它只返回我当前所在地点的索引 while chessboard[result[0], result[1]] != 0: for row in chessboard: for spot in row: if spot == 0:
while chessboard[result[0], result[1]] != 0:
for row in chessboard:
for spot in row:
if spot == 0:
location = np.where(chessboard == spot)
print(location)
for move in possible_moves:
if (location[0] + move[0]) < 0 or (location[1] + move[1]) < 0 or (location[0] + move[0]) > 7 or (location[1] + move[1]) > 7:
continue
else:
chessboard_updated[location[0] + move[0], location[1] + move[1]] = 0
chessboard = chessboard_updated
counter += 1
因为
location
返回
(array([5, 6, 7], dtype=int32), array([1, 2, 0], dtype=int32))
它返回5,6,7,而不是仅返回1个值
谢谢。总结一下评论
In [102]: arr = np.random.randint(0,4,(5,5))
In [103]: arr
Out[103]:
array([[1, 2, 1, 0, 2],
[1, 2, 3, 0, 0],
[3, 0, 1, 1, 1],
[0, 0, 3, 3, 0],
[1, 3, 2, 0, 1]])
np.其中
返回数组元组,告诉我们条件为真的位置:
In [104]: np.nonzero(arr==0)
Out[104]: (array([0, 1, 1, 2, 3, 3, 3, 4]), array([3, 3, 4, 1, 0, 1, 4, 3]))
该元组可直接用于索引源数组:
In [105]: arr[_]
Out[105]: array([0, 0, 0, 0, 0, 0, 0, 0])
我们可以使用np.transpose
(或argwhere
)将该元组转换为二维数组:
但这不能直接用于索引数组。我们必须迭代或使用列作为索引:
In [107]: [arr[tuple(ij)] for ij in _106]
Out[107]: [0, 0, 0, 0, 0, 0, 0, 0]
In [108]: arr[_106[0], _106[1]]
Out[108]: array([2, 3])
In [109]: arr[_106[:,0], _106[:,1]]
Out[109]: array([0, 0, 0, 0, 0, 0, 0, 0])
如果条件数组只有一个True
,则where
元组类似于:
(np.array([0]), np.array([4]))
两个大小为1的阵列
由于找到多个True
点,因此会出现歧义错误
if (location[0] + move[0]) < 0 or (location[1] + move[1]) < 0 ...
如果(位置[0]+移动[0])<0或(位置[1]+移动[1])<0。。。
位置[0]
是一个包含多个值的数组(位置[0]+move[0])<0
则是一个布尔数组,其值大于1。不能在Pythonif
或或
上下文中使用,这两种上下文都只需要一个真/假值。np.where(chessboard,0)
返回数组值为0的所有索引。由于在循环中将某些值设置为0,因此最终这将是多个索引。我不知道为什么这会让你感到惊讶。其中
给出了两个数组的元组,行
和列
索引。它得了2分<代码>棋盘[位置]应返回[0,0,0]
,棋盘上的3个零。您已经知道当前行索引,它是行
。对于列索引,在对行进行迭代时可以使用enumerate
。3个0位于(5,1)、(6,2)和(7,0)。您可以使用np.transpose(location)
(或np.argwhere
)获取这些。
(np.array([0]), np.array([4]))
if (location[0] + move[0]) < 0 or (location[1] + move[1]) < 0 ...