Home > OS >  Index to closest coordinate
Index to closest coordinate

Time:11-17

I have this function

A=[(1,2,3),(2,3,4)]
B=[(2,4,3),(1,8,1),(2,3,5),(1,5,3)]
def closestNew(A,B):
    C = {}
    for bp in B:
       closestDist = -1
       for ap in A:
          dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2))
          if(closestDist > dist or closestDist == -1):
             C[bp] = ap
             closestDist = dist
    return C

That will return the closest coordinate between the two lists.

Output:

{(1, 2, 3): (2, 4, 3), (2, 3, 4): (2, 3, 5)}

However, I want the index of array B (the points that matched with array A (check output)) as well in a seperate list, any ideas?

Return

idx=[0,2]

CodePudding user response:

A=[(1,2,3),(2,3,4)]
B=[(2,4,3),(1,8,1),(2,3,5),(1,5,3)]
C={(1, 2, 3): (2, 4, 3), (2, 3, 4): (2, 3, 5)}

C is a dictionary where it values correspond to points on B.

idx=[]   # an empty list
for x in C.values():
    idx.append(B.index(x))    # index function to find the index of values in B

print(idx)
#[0, 2]

CodePudding user response:

If you want to calcule the closest point to A, is better to have A as a outer loop and B as inside loop, in that way you can iterate for every A through all B's. Also you can use enumerate to know what index you are in the loop.


    a = [(1,2,3),(2,3,4)]
    b =[(2,4,3),(1,8,1),(2,3,5),(1,5,3)]
    # store reference for the min index-point
    index = []
    C = {}
    for indexA, ap in enumerate(a):
        # Assume the max distance
        closestDist = 1e9
        for indexB,bp in enumerate(b):
            dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2))
            if(dist < closestDist):
                C[ap] = bp
                closestDist = dist
                # Initialize the list if not have value for the i-th of A
                if indexA   1 > len(index):
                    index.append(indexB)
                else:
                    index[indexA] = indexB
    print(index)
    return C
  • Related