python find closest value in list code example
Example 1: select closest number in array python
import numpy as np
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
array = np.random.random(10)
print(array)
value = 0.5
print(find_nearest(array, value))
Example 2: python get nearest value in list
def takeClosest(num,collection):
return min(collection,key=lambda x:abs(x-num))
Example 3: how to get index of closest value in list python
min(range(len(a)), key=lambda i: abs(a[i]-11.5))