如何检查矩阵列表中是否包含矩阵 [英] How to Check if a Matrix is in a List of Matrices Python

查看:354
本文介绍了如何检查矩阵列表中是否包含矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是矩阵列表;

[matrix([[1, 0],
         [1, 0],
         [1, 0],
         [1, 0]]),
 matrix([[0, 0, 0, 0],
         [1, 1, 1, 1]]),
 matrix([[0, 1],
         [0, 1],
         [0, 1],
         [0, 1]]),
 matrix([[0, 0, 0, 0],
         [1, 1, 1, 1]]),
 matrix([[1, 1, 1, 1],
         [0, 0, 0, 0]])]

我想检查列表示例中是否已经有矩阵;

and I want to check if a matrix is already inside the list example;

a = matrix([[0, 0, 0, 1],
            [1, 1, 1, 0]])

因此,如果a在m中,则输出True,否则输出False

So if a is in m then print True else print False

推荐答案

我假设您正在使用NumPy.在这种情况下,请不要使用np.matrix,请使用np.array. np.matrix几乎仅是出于遗留原因而存在,并且具有不良功能.

I assume you are using NumPy. If this is the case, don't use np.matrix, use np.array. np.matrix exists almost exclusively for legacy reasons and has undesirable features.

您可以将any用于生成器理解和 np.array_equal .如果在输入列表中找到该数组,则会短路到True,否则返回False.

You can use any with a generator comprehension and np.array_equal. This will short-circuit to True if the array is found in the input list, otherwise return False.

import numpy as np

L = [np.array([[1, 0], [1, 0], [1, 0], [1, 0]]),
     np.array([[0, 0, 0, 0], [1, 1, 1, 1]]),
     np.array([[0, 1], [0, 1], [0, 1], [0, 1]]),
     np.array([[0, 0, 0, 0], [1, 1, 1, 1]]),
     np.array([[1, 1, 1, 1], [0, 0, 0, 0]])]

A = np.array([[0, 0, 0, 1], [1, 1, 1, 0]])

res = any(np.array_equal(A, i) for i in L)  # False

这篇关于如何检查矩阵列表中是否包含矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆