如何一个测试,如果Python中的矩阵只有1和0? [英] How does one test if a matrix in Python has only 1's and 0's?
本文介绍了如何一个测试,如果Python中的矩阵只有1和0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有这样一个矩阵:
Let's say I've got a matrix like this:
mat1 = np.array([1,0,1], [1,1,0], [0,0,0]);
和我有另外一个是这样的:
And I've got another one like this:
mat2 = np.array([0,1,0], [0,0,1], [1,1,1]);
我要检测是否像
np.add(mat1, mat2);
只有1或0,即一些1和0的一些公司,全部为0,或全部为1。
has only 1's or 0's, namely some 1's and some 0's, all 0's, or all 1's.
的 n.b 的 - 评你的code
n.b. - Comment your code.
推荐答案
这个怎么样:
>>> def check(matrix):
... # flatten up the matrix into one single list
... # and set on the list it should be [0,1] if it
... # contains only 0 and 1. Then do sum on that will
... # return 1
... if sum(set(sum(matrix,[]))) > 1:
... return False
... return True
...
>>>
>>> check([[1,0,1], [1,1,0], [0,0,0]])
True
>>> check([[1,0,1], [1,1,0], [0,0,2]])
False
>>> check([[1,0,1], [1,1,0], [0,0,3]])
False
>>>
这篇关于如何一个测试,如果Python中的矩阵只有1和0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文