写一个函数从python中的矩阵列表中分离出平方矩阵?

时间:2019-02-08 16:13:41

标签: python python-3.x

我正在尝试编写一个功能,如标题所示,但始终出现错误。这是我的代码:

all_matrices = [A,B,C,D,E,F,G] #these are all matrices defined above

def isSquare(matrices): 
    dims = []
    square_matrices = []
    i = 0

    for i in range(len(matrices)): 
        dims.append(np.shape(matrices[i]))

        if dims[i][0] == dims[i][1]:
            square_matrices.append(matrices[i])   

    return square_matrices

谢谢你们的第一个答案。现在我有一个新问题

我不断得到

  

“元组索引超出范围”

但是我不知道该如何解决。有什么建议么?我正在使用Spyder IDE。

2 个答案:

答案 0 :(得分:1)

由于您使用的是numpy,因此您可以像以下操作

all_matrices = [np.zeros((3,3)), np.zeros((3,2)), np.zeros((4,4))]

square_matrices = [m for m in all_matrices if m.shape[0] == m.shape[1]]
row_matrices = [m for m in all_matrices if m.shape[0] < m.shape[1]]
col_matrices = [m for m in all_matrices if m.shape[0] > m.shape[1]]

答案 1 :(得分:-1)

谢谢大家,我知道了!添加“范围”函数后,我注意到我的一个矩阵只有一个维度。那是导致“超出范围”的错误。我添加了另一个维度,效果很好。我不确定如何在不添加该尺寸的情况下进行操作。谢谢