[英]How to Check if a Matrix is in a List of Matrices Python
This is the list of matrices;这是矩阵列表;
[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]])
So if a is in m then print True else print False因此,如果 a 在 m 中,则打印 True 否则打印 False
I assume you are using NumPy.我假设您正在使用 NumPy。 If this is the case, don't use
np.matrix
, use np.array
.如果是这种情况,请不要使用
np.matrix
,而使用np.array
。 np.matrix
exists almost exclusively for legacy reasons and has undesirable features. np.matrix
几乎完全出于遗留原因而存在,并且具有不受欢迎的功能。
You can use any
with a generator comprehension and np.array_equal
.您可以将
any
与生成器理解和np.array_equal
。 This will short-circuit to True
if the array is found in the input list, otherwise return False
.如果在输入列表中找到数组,这将短路为
True
,否则返回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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.