I have 3 lists of 2d arrays of non-negative integers, e.g.
l1 = [(1, 7), (0, 55), (13, 3), (100, 100)]
l2 = [(5, 3), (40, 50), (11, 99), (555, 666)]
l3 = [(0, 40), (100, 555), (111, 999)]
They are not all of the same length, and I know nothing about the distribution of these points other than that all values are in some range [0, N] (N is not too big, 2500-3000-ish).
I'm looking for an efficient way to match point from l1 and l2 based on couples in l3:
if there is a pair in l3 such that the 1st coordinate is also a 1st coordinate in one of the pairs in l1 AND the 2nd coordinate (in l3 pair) is a 1st coordinate in a l2 pair - than the 3 pairs "match".
For example, from the lists above we'll get
matches = [[(0,55), (40,50), (0,40)], [(100,100), (555,666), (100, 555)]]
Here's what I have so far:
l1_left_coordinates = [p[0] for p in l1]
l2_left_coordinates = [p[0] for p in l2]
for p in l3:
left, right = p
try:
idx_of_left_in_l1 = l1_left_coordinates.index(left)
idx_of_right_in_l2 = l2_left_coordinates.index(right)
except ValueError:
continue
matches.append([l1[idx_of_left_in_l1], l2[idx_of_right_in_l2], p])
This works. But it means that for every l3 element I traverse both l1 and l2, resulting in O(n^2) worse-case runtime (where n is the size of the arrays). I wonder if there's a faster way to do this.