如何在 O(1) 中获得 numpy 中的反向映射?

Gul*_*zar 5 python arrays indexing numpy

我有一个 numpy 数组,其元素是唯一的,例如:

b = np.array([5, 4, 6, 8, 1, 2])

(Edit2:b可以有大数和浮点数。上面的例子是为了简单起见)

我得到的数字是 b 中的元素。

我想找到自己的指数b,这意味着我要反向映射,从价值指数,中b

我可以

for number in input:
    ind = np.where(number==b)
Run Code Online (Sandbox Code Playgroud)

每次调用where.

我还可以创建一个字典,

d = {}
for i, element in enumerate(list(b)):
    d[element] = i
Run Code Online (Sandbox Code Playgroud)

我可以在“预处理”时创建这个字典,但我仍然会留下一个看起来很奇怪的字典,在一个主要是 numpy 的代码中,这似乎(对我来说)不是 numpy 的使用方式。

如何在 numpy 中进行这种反向映射?

使用情况(需要 O(1) 时间和内存):

print("index of 8 is: ", foo(b, 8))
Run Code Online (Sandbox Code Playgroud)

这里解释的那样使用 in1d并不能解决我的问题。使用他们的例子:

b = np.array([1, 2, 3, 10, 4])
Run Code Online (Sandbox Code Playgroud)

我希望能够10在运行时在 O(1) 中找到例如b 中的索引。

做一个预处理动作

mapping = np.in1d(b, b).nonzero()[0]

>> [0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

(这可以使用完成np.arange(len(b))

并没有真正的帮助,因为当10作为输入进来时,使用这种方法不可能在 O(1) 时间内告诉它的索引。

Joe*_*don 0

如果您想要进行多次查找,您可以O(1)在初始O(n)遍历之后执行这些操作以创建查找字典。

b = np.array([5, 4, 6, 8, 1, 2])
lookup_dict = {e:i for i,e in enumerate(b)}
def foo(element):
    return lookup_dict[element]
Run Code Online (Sandbox Code Playgroud)

这适用于您的测试:

>>> print('index of 8 is:', foo(8))
index of 8 is:  3
Run Code Online (Sandbox Code Playgroud)

请注意,如果自b上次foo()调用以来有可能发生更改,我们必须重新创建字典。