简体   繁体   English

将矩阵与矩阵行中的元素匹配

[英]Matching array with elements in rows of matrix

I have a matrix x_faces with 3 columns and N elements (in this example 4). 我有一个包含3列和N个元素的矩阵x_faces (在此示例中为4)。 Per row I want to know if it contains any of the elements from array matches 我想知道每行是否包含数组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? 我可以想到一个for循环可以做到这一点,但是在python中有一种巧妙的方法吗?

You could use any() function for that purpose: 您可以为此目的使用any()函数:

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

Output: 输出:

[False, True, True, True]

You can use numpy and convert both arrays to 3D and compare them. 您可以使用numpy并将两个数组都转换为3D并进行比较。 Then I use sum to determine, whether any of the values in the last two axis is True: 然后,我使用sum来确定最后两个轴中的任何值是否为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)

我会做类似的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM