在数组中找到最接近给定值的值

时间:2019-05-04 17:09:02

标签: python-3.x

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

我试图获取最接近的值,但是我正在使用的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

4 个答案:

答案 0 :(得分:2)

如果可以保证输入列表是整数,则只需将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

答案 1 :(得分:1)

如果我对您的问题理解正确,则您想执行以下操作:

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

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

  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)
          break
      elif (midValue > value):
          midValue = constants[x]
          print("Nearest value ", midValue)
          break
  else:
      print('Nearest value ',constants[len(constants)-1])
      break

注意,我在两者之间使用break

输出:

Nearest midGirth  3

我也很困惑:

  

但是我得到4个输出。我想避免它

我想您只想显示:Nearest midGirth 3

答案 2 :(得分:0)

使用numpy:

import numpy as np
a=np.array([2,3,4,5])
a[np.abs((a-value)).argmin()]

因为它是标准的四舍五入,所以它将以2的值超过2.5。如果您需要使用小数模块的非标准2.5-> 3舍入舍入值

答案 3 :(得分:0)

您可以使用key函数的min找到差的最小值。如果是平局,Python 3的min()将返回遇到的第一个值。由于常量已排序,因此您可以反向浏览它们以获得舍入的效果:

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

# find the min of the differences between value and constants
# ties will find the largest value
min(reversed(constants), key = lambda x: abs(x-value))

# Result:  3