繁体   English   中英

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

[英]Matching array with elements in rows of matrix

我有一个包含3列和N个元素的矩阵x_faces (在此示例中为4)。 我想知道每行是否包含数组matches中的任何元素

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

该返回以下内容:

results = [
        False,
        True,
        True,
        True
    ]

我可以想到一个for循环可以做到这一点,但是在python中有一种巧妙的方法吗?

您可以为此目的使用any()函数:

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

输出:

[False, True, True, True]

您可以使用numpy并将两个数组都转换为3D并进行比较。 然后,我使用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