简体   繁体   English

如何从一组元组中找到一个值最接近给定元组的元组?

[英]How can I find a tuple from a group of tuples with the values closest to a given tuple?

I'm working with python and have a dict where the keys are tuples with 3 values each. 我正在使用python,并且有一个dict,其中键是每个具有3个值的元组。

I'm computing another tuple with 3 values, and I want to find the tuple in the keys of the dict with the closest values to this newly computed tuple. 我正在计算另一个具有3个值的元组,我想在字典键中找到与该新计算的元组最接近的值的元组。

How should I go about doing this? 我应该怎么做呢?

You could do something like this: 您可以执行以下操作:

def euclid2(x,y):
    return sum((xi-yi)**2 for xi,yi in zip(x,y))

def closestTuple(target,tuples, dist = euclid2):
    return min((dist(t,target),t) for t in tuples)[1]

#test:
target = (3,5,1)
tuples = [(3,1,2), (4,1,5), (6,1,7), (4,4,2), (1,5,7)]
print(closestTuple(target,tuples)) #prints (4,4,2)

This finds the tuple which is closest to the target tuple in the Euclidean metric. 这将找到在欧几里得度量标准中最接近目标元组的元组。 You could of course pass another function for the dist parameter. 您当然可以为dist参数传递另一个函数。

You are probably looking for the abs() of the difference, eg: 您可能正在寻找差异的abs() ,例如:

>>> from random import randint
>>> d = [tuple(randint(1, 20) for _ in range(3)) for _ in range(5)]
>>> d
[(4, 13, 10), (12, 18, 19), (11, 18, 8), (16, 17, 4), (2, 4, 10)]
>>> k = tuple(randint(1, 20) for _ in range(3))
>>> k
(14, 13, 1)
>>> min(d, key=lambda x: sum(abs(m-n) for m, n in zip(k, x)))
(16, 17, 4)

You could try the following (i used a list), and simply iterate over each element, and take the difference between each element in the tuple, then in the end sort the sums of the differences and look for the smallest amount 您可以尝试以下操作(我使用了一个列表),然后简单地遍历每个元素,并取而代之以元组中每个元素之间的差,然后最后对差的总和进行排序,并寻找最小的数量

a = [(1, 2, 3), (3, 4, 5), (5, 6, 7)]
b = (2, 4, 5)
c = []
for x in a:
     c[a.index(x)] = 0
     for i in range(len(x)):
            c[i]+=x[i]-b[i]

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

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