Reputation: 379
I have two 2D lists with x and y coordinates and I want to go through list1, and for each point find the closest (x, y) coordinates in list2. They're of different lengths, and it's okay if I don't use all the points of list2 or even if I reuse points, as long as I go through all the points only once in list1. I need the shift itself as well as the location in the lists of both points. Here's what I have done to find the shift:
s_x = ([1.0,2.0,3.0])
s_y = ([1.5,2.5,3.5])
SDSS_x = ([3.0,4.0,5.0])
SDSS_y = ([3.5,4.5,5.5])
list1 = zip(s_x,s_y)
list2 = zip(SDSS_x,SDSS_y)
shift = []
place_in_array = []
for num,val in enumerate(list1):
guess = 9999999999999.0
place_guess = 0
for index,line in enumerate(list2):
new_guess = math.hypot(line[0] - val[0], line[1] - val[1])
if new_guess < guess:
guess = new_guess
place_guess = index
shift.append(guess)
place_in_array.append(place_guess)
print shift
print place_in_array
but the output is this:
[2.8284271247461903, 1.4142135623730951, 0.0]
[0, 0, 0]
These are wrong, and I can't figure out what the problem is.
Upvotes: 2
Views: 1514
Reputation: 114098
def lazy_dist(p0):
return lambda p1:(p0[0] -p1[0])**2 + (p0[1] - p1[1])**2
closest_matches = {p0:min(list2,key=lazy_dist(p0)) for p0 in list1}
I think will do what you want (not very fast but it should work
Upvotes: 2
Reputation: 76381
There are specialized data structures for these geometric queries, with implementations that are debugged and efficient. Why not use them? sklearn.neighbors.BallTree
can do these types of queries, as well as sklearn.neighbors.KDTree
.
Upvotes: 3