简体   繁体   English

快速搜索数组中元素的索引

[英]Fast search for index of element in array

This is a rather simple problem but I have not found a way to solve it.这是一个相当简单的问题,但我还没有找到解决它的方法。 I need to find the indexes for all the elements in an array, that are stored in different (shuffled) arrays.我需要找到数组中所有元素的索引,这些元素存储在不同的(混洗的)arrays 中。

I can do that with the code below using the .index() method but this is very slow for not so large arrays.我可以使用下面的代码使用.index()方法来做到这一点,但对于不太大的 arrays 来说这非常慢。

Is there a way to improve the performance of this task?有没有办法提高这个任务的性能?

import numpy as np

N = 10000

# Initial array of unique integers
arr = np.arange(0, N)

# Arrays of shuffled elements in arr
np.random.shuffle(arr)
arr1 = np.array(arr)
np.random.shuffle(arr)
arr2 = np.array(arr)
np.random.shuffle(arr)
arr3 = np.array(arr)

# Convert to lists to be able to use the .index() method
arr1 = list(arr1)
arr2 = list(arr2)
arr3 = list(arr3)

# Obtain the sum of the positions in the 3 arrays, for each element in arr
idx_sum = []
for i in range(N):
    i0, i1, i2 = arr1.index(i), arr2.index(i), arr3.index(i)
    idx_sum.append(i0 + i1 + i2)
idx_sum = np.array(idx_sum)

For your prepared example, using argsort will help:对于您准备好的示例,使用argsort将有助于:

aa = np.argsort(arr1)
bb = np.argsort(arr2)
cc = np.argsort(arr3)

print(aa + bb + cc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM