本文介绍了从点列表中获取两个最接近的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个整数/浮点数列表,我需要找到最接近的两个数字.我该如何只使用嵌套的for循环呢?

I am given a list of integers/floats and I need to find the two numbers closest together. How would I do that using only nested for loops?

推荐答案

对于每个元素,您都必须将其与其他每个元素的距离与先前的最接近"值进行比较-每当此比较产生较小的值时,您还记得那对是最接近的两个"对.

For each element, you have to compare the distance of it to each of the other elements with your previous "closest" value - any time this comparison yields smaller values, you remember that pair as the "two closest" ones.

所以,这很简单:

def find_two_closest(numbers):
    # most distant points:
    delta = max(numbers), min(numbers)
    for i, element in enumerate(numbers):
        for j, sec_element in enumerate(numbers):
            if i == j:
                continue
            if abs(sec_element - element) < abs(delta[0] - delta[1]):
                delta = sec_element, element
    return delta

这篇关于从点列表中获取两个最接近的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 16:27