循环问题以及如何从给定值中选择最接近的值



我使用两个循环来进行一些计算。

但是我不能得到预期的结果。

下面是我的问题。

Calculation = []
Result= []
my_data = [1.2, 3, 5, 9, 13, 15, 17, 19]
for Ele in my_data:
    for i in range(3,16,3):
        #print i  # Here I get 3, 6, 9, 12, 15

我想从my_data中获取范围内最接近的值。因此,结果将是3、5(最接近6)、9、13(最接近12)、15。我将在结果中看到五个值。

然后我做一些计算得到这五个数字。

        CutPoint = int(round(abs(float(Ele) - i))) 

我用每个元素减去范围内的每个值,最小的值将是最接近的值。

        Calculation.append(CutPoint)
        if float(Ele) ==  i + min(Calculation): # Then I stuck here. Here is not entire correct. 
            TargetKey = str(Ele) # ps. Each element in my_data is just a key in my completed code. I will use this line to collect the data I need.
            Result.append(TargetKey)
print Result

我只能在结果中看到[‘3’,‘9’,‘15’]。5和13消失。

我一直呆在这里,不知道如何解决这个问题。

有人能帮忙吗?还是用更聪明的方式来实现同样的目标?

谢谢你的帮助。

如果my_data没有排序,您可以根据您的数字与my_data中所有数字之间的差进行排序,并取N个最接近的元素:

def closest(data, num, n):
    return sorted(data, key=lambda x: abs(x - num))[:n]

然而,这是非常天真的,因为每次你要求一组数字时,它都必须进行排序。一个更好的解决方案是先对元素进行排序,然后执行注释中指出的某种二进制搜索。

最新更新