bl3nd3d
bl3nd3d

Reputation: 7

Matching array with elements in rows of matrix

I have a matrix x_faces with 3 columns and N elements (in this example 4). Per row I want to know if it contains any of the elements from array matches

x_faces = [[   0,  43, 446],
           [   8,  43, 446],
           [   0,  10, 446],
           [   0,   5, 425]
          ]
matches = [8, 10, 44, 425, 440]

Which should return this:

results = [
        False,
        True,
        True,
        True
    ]

I can think of a for loop that does this, but is there a neat way to do this in python?

Upvotes: 0

Views: 387

Answers (3)

Giuseppe Cammarota
Giuseppe Cammarota

Reputation: 84

I would do something like:

result = [any([n in row for n in matches]) for row in x_faces]

Upvotes: 0

Ilja
Ilja

Reputation: 2114

You can use numpy and convert both arrays to 3D and compare them. Then I use sum to determine, whether any of the values in the last two axis is True:

x_faces = np.array([[   0,  43, 446],
           [   8,  43, 446],
           [   0,  10, 446],
           [   0,   5, 425]
          ])
matches = np.array([8, 10, 44, 425, 440])
shape1, shape2 = x_faces.shape, matches.shape
x_faces = x_faces.reshape((shape1 + (1, )))
mathes = matches.reshape((1, 1) + shape2)
equals = (x_faces == matches)
print np.sum(np.sum(equals, axis=-1), axis=-1, dtype=bool)

Upvotes: 0

xiº
xiº

Reputation: 4687

You could use any() function for that purpose:

result = [any(x in items for x in matches) for items in x_faces]

Output:

[False, True, True, True]

Upvotes: 2

Related Questions