Getting started:
For a given number x (say -5) I want to know which element of a list y (say [2, -6]), minimizes the value of distance function d (say the absolute value) which applied on x and all elements of y. My current solution to this problem is
x = -5
y = [2, -6]
def d(a1, a2):
return abs(a1-a2) # more complicated in real application
min(y, key = lambda _: d(_, x)) # correctly returns -6
Next level: x is actually a list (say [1, 5, -10]), so I build a list comprehension on top my previous solution:
x = [1, 5, -10]
[min(y, key = lambda _: d(_, xindex)) for xindex in x] # correctly returns [2, 2, -6]
As this type of problem seems quite basic to me, I expect a simple solution for this problem (like argmin(list1=x, list2=y, function=d)). Here is a question where it is shown how a custom distance matrix can be build. But this alone (the step from the distance matrix to the argmins would also have to be done) seems too be more complicated than my code.
Overall my question is: is my code fine, or is there a nicer solution?
[2, 2, -6]) that minimizes the distance. \$\endgroup\$