簡體   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