python - 在数组中找到最接近给定值的值
问题描述
我想从给定值的数组列表中检索最接近的值。
我试图检索最接近的值,但我正在使用的 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
解决方案
如果您保证输入列表是一个整数,只需将值转换为它的上限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
推荐阅读
- java - 在静态上下文 (ARCore) 中使用 MediaPlayer 的问题
- spring-boot - 如何在运行时选择要调用的spring bean
- python - 在 Python 中通过 json 格式发送脚本文件
- c# - 在 C# 中使用 if else 语句以实现统一时,运算符“&&”不能应用于“布尔”和“字符串”类型的操作数
- javascript - 使用 React.cloneElement() 保存的 Refs
- javascript - 如何在html中获取数组中的两个条目?
- python - 为什么这个反转整数的代码打印'inf'?
- azure-aks - azure-kubernetes-service 在 webconsole 上创建失败
- node.js - 在没有“id”字段的弹性搜索中更新文档的其他方法
- angular - 无法在 Angular 中读取 null 的属性