寻找以下算法.

例如,给出以下无序列表:

main_list = np.array([100,200,400,1000,800,900,700,600,500,300])

并且给定对应于列表np.array([400, 900, 600, 300])的查询列表元素q = np.array([2,5,7,9]),直接从Main_List获得排序的元素和排序的位置

np.array([300, 400, 600, 900])
np.array([9,2,7,5])

主要条件:仅使用预计算的排序数组,以避免每次获得新查询时都执行排序操作.

编辑:numpy解决方案(谢谢@ cary—swoveland!)

首先预先计算已排序参数的已排序.这是脱机步骤:

argsort = np.argsort(main_list)
argsort_argsort = np.argsort(argsort)

然后在查询时:

q = np.array([2,5,7,9])

new_array = np.full(main_list.shape[0], -1)
new_array[argsort_argsort[q]] = q

sorted_q = new_array[new_array != -1]
sorted_values = main_list[sorted_q]

print(sorted_q)
print(sorted_values)

结果:

[9 2 7 5]
[300 400 600 900]

推荐答案

下面是Ruby的一个解决方案,我希望它可以相当容易地转换成其他语言.

我们得到以下信息.

arr = [100, 200, 400, 1000, 800, 900, 700, 600, 500, 300]

Step 1: Produce an array containing 所以rted indices of 100

a = arr.each_index.所以rt_by { |i| arr[i] }
  #=> [0, 1, 9, 2, 8, 7, 6, 4, 5, 3]

这意味着

arr[a[i]] = arr.所以rt[i] 

如果i = 2,例如,

arr[a[2]] #=> arr[9] => 300
arr.所以rt[2] = 300

Step 2: Create an array of orderings of offsets

b = (0..arr.size-1).所以rt_by { |i| a[i] }
  #=> [0, 1, 3, 9, 7, 8, 6, 5, 4, 2]

b[2] #=> 3就是arr[2] = arr.所以rt[3].

Step 3: Construct the desired arrays for each given array of indices

该运算的时间复杂度为O(N),n为数组的大小.

假设

indices = [2,5,7,9]

所以

arr.values_at(*indices)
  #=> [400, 900, 600, 300]

首先创建一个包含arr.size个元素的数组,所有元素都等于nil.

c = Array.new(arr.size)
  #=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

现在,在正确的位置,用元素indices替换元素c.

indices.each { |idx| c[b[idx]] = idx }

c #=> [nil, nil, 9, 2, nil, 7, nil, nil, 5, nil]

最后,删除nil个元素.

c.compact
  #=> [9, 2, 7, 5]

arr.values_at(*c)
  #=> [300, 400, 600, 900]

同样如果

indices = [5, 3, 1, 7, 2]

然后

arr.values_at(*indices)
  #=> [900, 1000, 200, 600, 400]
c = Array.new(arr.size)
  #=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
indices.each { |idx| c[b[idx]] = idx }
c #=> [nil,   1, nil,   2, nil,   7, nil, nil,   5,   3]
d = c.compact
  #=> [1, 2, 7, 5, 3]
arr.values_at(*d)
  #=> [200, 400, 600, 900, 1000]

Python相关问答推荐

具有多个选项的计数_匹配

通过Selenium从页面获取所有H2元素

创建可序列化数据模型的最佳方法

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

Python逻辑操作作为Pandas中的条件

lityter不让我输入左边的方括号,'

在Python中调用变量(特别是Tkinter)

numpy.unique如何消除重复列?

Pandas:计算中间时间条目的总时间增量

PYTHON、VLC、RTSP.屏幕截图不起作用

统计numpy. ndarray中的项目列表出现次数的最快方法

每次查询的流通股数量

pytest、xdist和共享生成的文件依赖项

有没有一种方法可以在朗肯代理中集成向量嵌入

如何将列表从a迭代到z-以抓取数据并将其转换为DataFrame?

无法使用请求模块从网页上抓取一些产品的名称

Numpy`astype(Int)`给出`np.int64`而不是`int`-怎么办?

我可以同时更改多个图像吗?

如何在Polars中处理用户自定义函数的多行结果?

Sknowled线性回归()不需要迭代和学习率作为参数