4

在下面显示的矩阵中,我想匹配两个矩阵中的第一个元素。如果第一个元素相等,那么我需要匹配两个矩阵中的第二个元素,依此类推..如果元素相同,则打印“相同”,否则打印“不一样”....

我的问题是,对于 m*n where m=n always

 for i in a1:
     for j in a2:
        if i!=j:
           break
         else:
           //compare the next corresponding columns and print "same" or "not same"


 a1=[1,44,55],[2,33,66],[3,77,91]  

 a2=[1,44,55],[2,45,66],[3,77,91]    

 OR 

 a1=[1,44,55]
    [2,33,66]
    [3,77,91]  

 a2=[1,44,55]
    [2,45,66]
    [3,77,91]  
4

5 回答 5

14

由于浮点舍入错误,您可能会遇到一些问题。

>>> import numpy as np
>>> x = np.array(1.1)
>>> print x * x
1.21
>>> x * x == 1.21
False
>>> x * x
1.2100000000000002
>>> np.allclose(x * x, 1.21)
True

要比较两个数值矩阵是否相等,建议您使用np.allclose()

>>> import numpy as np
>>> x = np.array([[1.1, 1.3], [1.3, 1.1]])
>>> y = np.array([[1.21, 1.69], [1.69, 1.21]])
>>> x * x
array([[ 1.21,  1.69],
       [ 1.69,  1.21]])
>>> x * x == y
array([[False, False],
       [False, False]], dtype=bool)
>>> np.allclose(x * x, y)
True
于 2012-08-02T17:48:33.870 回答
9

有什么问题a1 == a2

In [1]: a1=[[1,44,55],
   ...:     [2,33,66],
   ...:     [3,77,91]]

In [2]: a2=[[1,44,55],
   ...:     [2,45,66], # <- second element differs
   ...:     [3,77,91]]

In [3]: a1 == a2
Out[3]: False

In [4]: a1=[[1,44,55],
   ...:     [2,33,66],
   ...:     [3,77,91]]

In [5]: a2=[[1,44,55],
   ...:     [2,33,66],
   ...:     [3,77,91]]

In [6]: a1 == a2
Out[6]: True
于 2012-06-01T13:41:24.553 回答
5

如果您使用的是 numpy 数组,请使用.all()and .any()

x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[1, 2, 3], [4, 5, 6]])
x.all() == y.all()
>> True

x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[11, 21, 31], [41, 4, 61]])
x.any() == y.any()
>> True (since x[1][0] == y[1][1])
于 2020-01-27T03:40:07.690 回答
1

如果你想对矩阵进行操作,numpy是你可以使用的最好的库

In [11]: a = numpy.matrix([[1,44,55],
    ...:                   [2,33,66],
    ...:                   [3,77,91]])

In [12]: b = numpy.matrix([[1,44,55],
    ...:                   [2,45,66],
    ...:                   [3,77,91]])

In [13]: a == b
Out[13]: 
matrix([[ True,  True,  True],
        [ True, False,  True],
        [ True,  True,  True]], dtype=bool)
于 2012-06-01T13:45:10.460 回答
0

以下是不使用 numpy 的列表解决方案。

def isIdentical(a: list, b: list) -> bool:
    rows, cols = len(a), len(a[0])
    return all([a[i][j] == b[i][j] for j in range(cols) for i in range(rows)])
于 2020-12-11T13:18:45.680 回答