首页 > 解决方案 > 在数组中找到最接近给定值的值

问题描述

我想从给定值的数组列表中检索最接近的值。

我试图检索最接近的值,但我正在使用的 for 循环遇到问题。

def get_total_price_iot(self):
    """calculate the price """


    value = 2.5
    constants = [2,3,4,5]

    for x in range(len(constants)):
      if(value<constants[0]):
           print('Nearest Value ',constants[0])

      elif(value>=constants[x] and value<=constants[x+1]):
          midValue = (constants[x] + constants[x + 1]) / 2

          if (midValue <= value):
              midValue = constants[x + 1];
              print("Nearest midGirth ", midValue)
          elif (midValue > value):
              midValue = constants[x]
              print("Nearest value ", midValue)


      else:
          print('Nearest value ',constants[len(constants)-1])

我的预期结果是3,但我得到4的是输出。

这是我的输出:

Nearest midGirth  3
Nearest value  5
Nearest value  5
Nearest value  5

标签: pythonpython-3.x

解决方案


如果您保证输入列表是一个整数,只需将值转换为它的上限math.ceil并将数字与值进行比较

import math

value = 2.5
constants = [2,3,4,5]

for item in constants:
    if item == math.ceil(value):
        print(item)

答案会在3这里

一种优化的方法是计算一个difference数组,即 value 和每个元素之间的差异,对其进行排序并返回2nd element+value

def get_nearest(value, constants):

    #Calculate the difference array between value and each element in constants
    diffs = [item-value for item in constants]

    #Sort it
    diffs = sorted(diffs)

    #Return the second element+value
    return diffs[1]+value

输出将是

print(get_nearest(2.5, [2,3,4,5]))
#3.0
print(get_nearest(2.5, [2,13,4,5]))
#4.0
print(get_nearest(2.1, [2,13,4,5]))
#4.0

推荐阅读