这是我的代码:
import numpy as np
OPEN = np.full((10, 2), np.inf)
CLOSED = np.zeros_like(OPEN, dtype = np.int)
OPEN[0][0] = 0.0
OPEN[0][1] = 1.0
OPEN[1][0] = 1.0
CLOSED[0][0] = 1
print("OPEN:")
print(OPEN)
print("")
print("CLOSED:")
print(CLOSED)
print("-------")
# Some magic here:
# Expected output:
print("Expected Output:")
print("[1, 0] or [0, 1]")
print("-------")
# Useful function - find the minimum value in an array:
min_in_OPEN = np.unravel_index(OPEN.argmin(), OPEN.shape)
min_in_OPEN = [min_in_OPEN[0],
min_in_OPEN[1]] # just foe better representation
print("Current Output:")
print(min_in_OPEN)
这是代码的输出:
OPEN:
[[ 0. 1.]
[ 1. inf]
[inf inf]
[inf inf]
[inf inf]
[inf inf]
[inf inf]
[inf inf]
[inf inf]
[inf inf]]
CLOSED:
[[1 0]
[0 0]
[0 0]
[0 0]
[0 0]
[0 0]
[0 0]
[0 0]
[0 0]
[0 0]]
-------
Expected Output:
[1, 0] or [0, 1]
-------
Current Output:
[0, 0]
如代码所解释的,我需要获取数组“ OPEN”中最小值的索引,其中在列表“ CLOSED”中使用的相同索引指向“ 0”而不是“ 1”
不能将列表OPEN中的值更改为其他值/数据类型,但可以将列表CLOSED中的值更改为其他值/数据类型。例如,CLSOED列表也可能看起来像这样:
[[ True False]
[False False]
[False False]
[False False]
[False False]
[False False]
[False False]
[False False]
[False False]
[False False]]
答案 0 :(得分:2)
您可以通过将第一个数组(OPEN)约束到希望第二个数组(CLOSED)为真的位置来实现此目的:
constrained = OPEN[CLOSED!=1]
,然后使用argmin()
找到最小值的第一个位置:
pos = constrained.argmin()
唯一的问题是constrained
是一维数组,这意味着您需要将pos
映射回原始OPEN
中的索引对。您可以使用np.where()
进行此操作,这将返回满足条件的索引数组的元组:
valid_positions = np.where(CLOSED!=1)
将此元组转换为数组并用pos
对其进行索引将为您提供与pos
相对应的索引对:
idx = np.asarray(valid_positions)[:,pos]