I am writing some code in Python that takes a set of [x,y] coordinates (in an inventory of tuples) and likewise an x-value. I would like to seek out the 2 closest x coordinates to my x-value.
To seek out the closest x, I created an inventory of all of the x-coordinates, used that listing to create a lambda perform that discovered the closest x to my x-value, after which discovered the index of that x.
Discovering the 2nd closest worth was a bit trickier. I created a brand new listing that excluded the closest x and adopted the identical course of.
Code is beneath. Any solutions on methods to enhance this or make it extra environment friendly?
def closest_2_points(list_of_tuples, x_value): x_points =  for i in list_of_tuples: x_points.append(i) # discover closest level closest_xpoint_1 = min(x_points, key=lambda z:abs(z-x_value)) closest_xpoint_1_idx = x_points.index(closest_xpoint_1) # discover 2nd closest level x_points_2 = [x for x in x_points if x != closest_xpoint_1] closest_xpoint_2 = min(x_points_2, key=lambda z:abs(z-x_value)) closest_xpoint_2_idx = x_points.index(closest_xpoint_2) return closest_xpoint_1, closest_xpoint_2, closest_xpoint_1_idx, closest_xpoint_2_idx
When working the perform, it ought to look one thing like this: