Home > Blockchain >  Python: finding the closest value in a list less than or greater than a input value, excluding the i
Python: finding the closest value in a list less than or greater than a input value, excluding the i

Time:07-13

Is there a way to find the closest value from a list that is either less than or greater than a value gathered by input? The input value has to be excluded from the possible values.

I've used this, but it gives back the input value if it is in the list. I do not want to get that value back. I'm trying to find the closest value lees than or greater than the input.

closeVal = lambda myList : abs(myList - inputValue) 

closeVal = min(myList, key=closeVal)

Thanks!

CodePudding user response:

Filter out the input values before getting the minimum.

closeVal = min([x for x in myList if x != inputValue], key=lambda y: abs(inputValue - y))
  • Related