I have 2 lists of positional tuples (x,y data). I would like to return 2 arrays or lists of the indexes for positions (or a tuple) that are in both lists. However the positional data values will not be exactly equal, there will be an uncertianty of +/- 4 on both the x and y coordinates.
For example:
A=[(1168.593,9.874), (1799.244,40.201),(780.533,12.636)]
B=[(1170.909,8.194), (793.149,10.885), (1801.493,41.603)]
it should return:
c=[(0,0),(1,2)]
or:
d=[0,1] #indexes for A
e=[0,2] #indexes for B
Either one would be fine to use.
Is there a function in Python you can use that returns the indexes of matching data in 2 lists, by specifying a +/- value as well?
I need to do this for 3 lists of ~400 tuples each, which are not equal in size.
I was thinking of even using something like:
common=[a in A for a in B]
and somehow specifying a range for a
, just looking at the x and y data and return the indices instead of true/false, but I really don't know how to approach this. Is a loop the only way to do this, by looking at each value separately, getting a difference between them and seeing if this is < 4, then getting the indexes?
How about a brute-force solution?
In [5]: c = []
In [6]: for i, (x1, y1) in enumerate(A):
...: for j, (x2, y2) in enumerate(B):
...: if (x1 - 4 <= x2 <= x1 + 4) and (y1 - 4 <= y2 <= y1 + 4):
...: c.append((i,j))
...:
...:
In [7]: c
Out[7]: [(0, 0), (1, 2)]
Of course, you can replace the conditional with whatever you want. Likely, using math.isclose
is a good idea. There may be a better numpy
way of doing this in a vectorized fashion. But this should work if efficiency isn't a concern.