Python offers a number of features to help find the nearest value and its index in a list. Examples:
Table of contents
Let's create a list of random floats between 0 and 10:
import random
l = [round(random.uniform(0,10),2) for i in range(10)]
this code will generate for example:
[6.65, 9.71, 0.86, 6.43, 3.02, 2.25, 6.94, 9.8, 8.96, 9.67]
Goal: find nearest value of:
value = 5.5
and its index
Using a Lambda expression
One approach is to use a Lambda expression which provide a simple and powerful way to create anonymous functions:
min(range(len(l)), key=lambda i: abs(l[i]-value))
returns
3
Note that l[3]
6.43
Using numpy with argmin()
Another approach is to use the numpy argmin()
function, which returns the index of the minimum value in an array or list. For example
np.argmin([ abs(i-value) for i in l])
returns
3
Create a loop
Although not the most ideal solution, this approach offers a greater insight into the underlying logic:
res = []
for idx in range(len(l)):
diff = abs(l[idx]-value)
res.append((diff,idx))
min(res)[1]
returns
3
References
Links | Site |
---|---|
argmin() | numpy.org |
lambda | docs.python.org |
random.uniform | docs.python.org |