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

2024-05-19 07:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我用两个循环来做一些计算。你知道吗

但是我不能得到预期的结果。你知道吗

下面是我的问题。你知道吗

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

我想从我的\u数据中得到最接近的值。所以结果是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消失了。你知道吗

我被困在这里,不知道如何解决这个问题。你知道吗

有人能帮忙吗?或者用更聪明的方法来实现同样的目标?你知道吗

谢谢你的帮助。你知道吗


Tags: infordatahereismyrangeresult
1条回答
网友
1楼 · 发布于 2024-05-19 07:23:43

如果my_data未排序,则可以按您的数字与my_data中所有数字之间的差值排序,并取N个最接近的元素:

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

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

相关问题 更多 >

    热门问题