Python:如何在两个单独的数组之间找到两个相等/最接近的值? [英] Python: How to find two equal/closest values between two separate arrays?
问题描述
假设我们有两个长度相等的数组:
Let's say we have two arrays of equal length:
arr1 = (21, 2, 3, 5, 13)
arr2 = (10, 4.5, 9, 12, 20)
arr1
中的哪个变量与 arr2
中的变量等于/最接近?
Which variable from arr1
is equal / closest to a variable from arr2
?
通过查看这两个列表,我们可以轻松地说出最接近的数字是 4.5 和 5 .我试图实现一个函数,该函数在给定两个列表的情况下返回两个最接近的值,对于上面的示例来说,它有点有效,但由于它不是最优的,所以几乎不是解决方案.而且,当我们对数组进行如下更改时,您可以轻松地检查该函数是否失败:
Looking at these two lists we can easily say that the closest numbers are 4.5 and 5. I've tried to implement a function that returns two closest values given two lists and it kinda works for the examples above, but it is barely a solution because it is not optimal. And you can easily check that the function fails when we slightly change the arrays like this:
arr1 = (21, 2, 3, 5, 13)
arr2 = (10, 4.5, 9, 12, 18)
函数返回的值为13和18
the values the function returns are 13 and 18
这是函数:
def get_nearest(arr1, arr2):
lr = [[0, 0, 0]]
for x1 in arr1:
for x2 in arr2:
r = (x1 / x2 % (x1 + x2))
print x1, x2, r
if r <= 1 and r >= lr[0][2]:
lr.pop()
lr.append([x1, x2, r])
return lr
您能提出更好的选择吗?
Can you come up with a better one?
推荐答案
速度有问题吗?你在乎领带吗?如果没有,那像这样的简单东西怎么办
Is speed an issue? Do you care about ties? If not, what about something simple like
from itertools import product
sorted(product(arr1, arr2), key=lambda t: abs(t[0]-t[1]))[0]
两者都
arr1 = (21, 2, 3, 5, 13)
arr2 = (10, 4.5, 9, 12, 20)
和
arr1 = (21, 2, 3, 5, 13)
arr2 = (10, 4.5, 9, 12, 18)
这产生
(5, 4.5)
说明:
product(arr1, arr2) = [(a1, a2) for (a1, a2) in product(arr1, arr2)]
产生所有 N ** 2
对数字的列表:
yields a list of all N**2
pairs of numbers:
[(21, 10), (21, 4.5), ..., (13, 12), (13, 20)]
然后,我们使用 sorted
按绝对差( | a1-a2 |
)对它们进行排序.通过传递 sorted
和 key
关键字,我们告诉 sorted
使用排序标准 lambda t:abs(t [0]-t[1])
.绝对差最小的那对被放置在排序数组的第一个索引中,因此我们可以通过在末尾添加 [0]
来抓住它.
Then we sort them by the absolute difference (|a1 - a2|
) using sorted
. By passing sorted
the key
keyword, we tell sorted
to use the sorting criteria lambda t: abs(t[0] - t[1])
. The pair with the smallest absolute difference is placed in the first index of the sorted array, so we can grab it by tacking [0]
on the end.
正如Piotr在评论中所建议的那样,您可以将 key = func
馈入 min
和 max
,从而大大加快了速度.尝试尝试:
As suggested by Piotr in the comments, you can feed a key=func
to min
and max
, which speeds this up considerably. Try instead:
from itertools import product
min(product(arr1, arr2), key=lambda t: abs(t[0]-t[1]))[0]
这篇关于Python:如何在两个单独的数组之间找到两个相等/最接近的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!