Home > Mobile >  Labeling Coordinate Based on Dictionary Information
Labeling Coordinate Based on Dictionary Information

Time:11-16

Below is my dictionary information

Z = {1: [[7,0],[7,1]], 
     2: [[3,4],[2,4]],
     3: [[0,3],[4,6]]} 

Below is my coordinate array

X = [[7,0],[0,3],[3,4],[4,6],[7,1],[2,4]]

What I want to produce is this

 Y = [1,3,2,3,1,2]

So basically Y is labeling coordinate X based on information from Z. How can I achieve this in python?

CodePudding user response:

Here's a quick poke at your problem:

Z = {1: [[7,0],[7,1]], 
     2: [[3,4],[2,4]],
     3: [[0,3],[4,6]]} 
# Below is my coordinate array

X = [[7,0],[0,3],[3,4],[4,6],[7,1],[2,4]]

# What I want to produce is this

Y1 = [1,3,2,3,1,2]

Y = []
for coord in X:
    hit = None
    for k in Z:
        if coord in Z[k]:
            hit = k
            break
    Y.append(hit)

print(Y)
print(Y1)

CodePudding user response:

If the structures are not too big, you can invert the Z and make the pairs into the dictionary keys. But lists are mutable, so you have to convert them to tuples:

Z = {1: [[7,0],[7,1]], 
     2: [[3,4],[2,4]],
     3: [[0,3],[4,6]]}
X = [[7,0],[0,3],[3,4],[4,6],[7,1],[2,4]]

z = {tuple(p):k for k,l in Z.items() for p in l}
{(7, 0): 1, (7, 1): 1, (3, 4): 2, (2, 4): 2, (0, 3): 3, (4, 6): 3}

Y = [z[tuple(p)] for p in X]
[1, 3, 2, 3, 1, 2]
  • Related