gpt4 book ai didi

python - 确定两个列表/数组的混洗索引

转载 作者:太空狗 更新时间:2023-10-30 00:22:42 25 4
gpt4 key购买 nike

作为挑战,我给自己出了这个问题:

给定 2 个列表 A 和 B,其中 B 是 A 的混排版本,想法是找出混排后的索引。

例如:

A = [10, 40, 30, 2]
B = [30, 2, 10, 40]

result = [2, 3, 0, 1]
A[2] A[3] A[0] A[1]
|| || || ||
30 2 10 40

请注意,相同元素的关系可以任意解决。

我想出了一个 solution这涉及使用字典来存储索引。这个问题还有哪些其他可能的解决方案?使用库的解决方案也有效。 Numpy、pandas,什么都好。

最佳答案

我们可以利用np.searchsorted及其可选的 sorter 参数 -

sidx = np.argsort(B)
out = sidx[np.searchsorted(B,A, sorter=sidx)]

sample 运行-

In [19]: A = [10, 40, 30, 2, 40]
...: B = [30, 2, 10, 40]
...:

In [20]: sidx = np.argsort(B)

In [21]: sidx[np.searchsorted(B,A, sorter=sidx)]
Out[21]: array([2, 3, 0, 1, 3])

关于python - 确定两个列表/数组的混洗索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45830838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com