从元组中返回对的另一个值,该值最接近某个数字

Returning the other value of the pair from a tuple, which has closest value to certain number

我有一个 listtuples 像这样:

[(78, 10), (84, 11), (75, 12), (78, 13), (75, 14), (77, 15), (79, 16), (81, 17), (83, 18), (85, 19)]

如果任何 tuples 中的第一个数字是 closest/equal 到某个特定数字,return 来自该元组的另一对值,我该怎么做?

例如上面的列表:

某数:79 那么它应该是上面列表中的 return 16。

谢谢!

试试这个解决方案:

l = [(78, 10), (84, 11), (75, 12), (78, 13), (75, 14), (77, 15), (79, 16), (81, 17), (83, 18), (85, 19)]
n = 79
diff = 10**6
ans = 0
for i in l:
    if abs(n-i[0])< diff:
        diff = abs(n-i[0])
        ans = i[1]
        
print(ans)
        

输出:

16

你有几个选择。

方法一:

遍历列表并检查最小差异。

def return_closest_pair(data: list, target: int) -> int:
    closest, other = data[0]
    closest_diff = abs(closest - target)
    rest = iter(data[1:])
    for left, right in rest:
        diff = abs(left - target)
        if diff < closest_diff:
            closest, other = left, right
    return other

>>> return_closest_pair(data, 79)

方法二:

min 函数写一个自定义键,正如您最初尝试的那样。

def find_closest_to(target):
    def comp(tup):
        left, right = tup
        return abs(left - target)
    return comp

>>> min(data, key=find_closest_to(79))[0]
16