Reputation: 9
I would like know how I can find the nearest solution.
For example, I have a list like it :
list=[1,2,3,4,5,6,7]
And ofc my list is really big , and I want find the nearest solution.
If I say at my algorithm, " find me the number 8" But I have no number 8, so he will return me 7 because 7 is the nearest from 8.
Thanks for reading me !
Upvotes: 2
Views: 57
Reputation: 415
min(list, key= lambda x: abs(solution - x))
this code returns the object in his list that his abs distance from the solution is the smallest.
Upvotes: 2
Reputation: 556
Try this :
my_list=[1,2,3,4,5,6,7]
target = 8
dist = [abs(i - target) for i in my_list]
min_index = dist.index(min(dist))
print(my_list[min_index])
Upvotes: 1