编辑我的问题以使其更加清晰,因为我无法获得第一个工作答案。我正在尝试制作一个 N 维查找表,根据 N 个 True/False 值的输入列表从中查找一个值。为此,我创建了一个 N 维数组,其中每个维度的长度为 2 - 一个值表示 False (=0),一个值表示 True (=1)import numpy as npimport randomdims = 3values = range(pow(2,dims))lookup=np.reshape(values,np.tile(2,dims)) #this makes a 2x2x2x... arraycondition=random.choices([True,False],k=dims) #this makes a 1d list of bools条件中的布尔值现在应该指定要查找的索引。以 N=3 为例:如果条件 =(True,False,True),我想要查找[1,0,1]。只需使用lookup[condition.astype(int)]不起作用,因为 numpy 不会将 1x3 数组解释为索引。lookup[condition[0],condition[1],condition[2]]作品。但我还没弄清楚如何在 N 维上写这个
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
手动将其转换为 int 元组可以实现您所寻求的索引。测试下面的代码。
import numpy as np
# your example had d=3, but you may have something else.
# this is just creation of some random data...
d=3
answers = np.random.normal(size=[2] * d)
truth = tuple(np.random.choice([True, False], replace=True, size=d))
# manual conversion to int-tuple is needed, for numpy to understand that it
# is a indexing tuple.
# the box at the top of https://numpy.org/doc/stable/reference/arrays.indexing.html
# says that tuple indexing is just like normal indexing, and in that case, we
# need to have normal ints.
idx = tuple(int(b) for b in truth)
answer = answers[idx]
print(answer)
添加回答
举报
0/150
提交
取消