我正在尝试在我的脚本中添加一个算法,该算法可以从少数变量中找到最接近的整数值,例如:
int = 700
value1 = 400
value2 = 500
value6 = 600
如何创建一个脚本,将value6
作为所有值变量中最接近的值?
答案 0 :(得分:12)
将min
与适当的关键功能一起使用,例如i
的差异abs(你真的不应该将其命名为int
):
i = 700 # don't shadow built-in name int
values = (value1, value2, ...) # consider using a list/tuple from the beginning
nearest = min(values, key=lambda v: abs(i-v))
> nearest
600
答案 1 :(得分:5)
如果您按顺序保留数字并Removed height property
,则可以在 log n 时间内执行此操作i = 540
value1 = 400
value2 = 500
value6 = 600
lst = [value1, value2, value6]
from bisect import bisect
ind = bisect(lst, i, hi=len(lst) - 1)
print(min((lst[ind], lst[ind - 1]), key=lambda x: abs(x-i)))
答案 2 :(得分:2)
作为python的相对初学者,我确信这可以改进。其他答案很好,但只有两个值相等的距离时才返回输入下最近的值。
(以上编辑为了回应Padraic Cunningham的清晰度)
#!/usr/bin/python3
values = (100, 200, 300, 400, 500, 600, 700)
i = 245
nearest_under = min(values, key=lambda v: abs(v-i))
nearest_over = min(values, key=lambda v: abs(v-i) and v<i)
under_distance = i - nearest_under
over_distance = nearest_over - i
if (under_distance == over_distance):
nearest = (nearest_under, nearest_over)
elif under_distance < over_distance:
nearest = (nearest_under, )
else:
nearest = (nearest_over, )
print (nearest)
答案 3 :(得分:1)
您可以使用min
- 函数和key-argument:
values = [400, 500, 600]
int = 700
nearest = min(values, key=lambda v: abs(v-int))
答案 4 :(得分:1)
你也可以试试这个更长的路,为了学习目的,我想: