Introduction to the problem
I have a list of numbers and I want to, given certain value, get the closest value in the list that fulfil the condition. This is: the difference between closest value and value itself should be less than 0.5
What have I done
I'm new with lambda expressions so may be I don't understand the working process of this function. I have based (copy) my code on this answer: from list of integers, get number closest to a given value
def min_in_limits(value,list):
new_val = min(list, key=lambda x: float(abs(float(x)-float(value)))<0.5)
return new_val
So, when I give these inputs:
list = [9,11,13]
value = 8.9
Function min_in_limits returns 11, instead of 9
When evaluating step by step lambda returns:
True, False, False
Why is this failing?
Less elegant, but functional
def less_elegant(value,list):
dictionary = {}
for i in list:
temp = float(abs(float(i)-float(value)))
if temp < 0.5:
dictionary.update({temp:i})
keys = dictionary.keys()
return(dictionary[min(keys)])
Thank you!