检查矩阵是否为正方形? (Python) [英] Check if a matrix is square? (Python)
本文介绍了检查矩阵是否为正方形? (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测试[[5,6],[7,8]]的2x2矩阵,看看它是否是正方形.
I want to test a 2x2 matrix of [[5,6],[7,8]] to see if it's a square.
我运行我的代码,我应该得到True,但是我得到False ...
I run my code and I'm supposed to get True but I got False instead...
def square(sq):
for element in sq:
if element:
return False
return True
推荐答案
如果要检查矩阵是否为NxN,可以使用:
If you want to check whether a matrix is NxN, you can use:
def isSquare (m): return all (len (row) == len (m) for row in m)
正如您在评论中所说:如果所有行的长度等于行数.
As you said in your comment: if the length of all rows equals the number of rows.
这篇关于检查矩阵是否为正方形? (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文