如何测试Python中的矩阵是否仅包含1和0?
假设我有一个这样的矩阵:
mat1 = np.array([1,0,1], [1,1,0], [0,0,0]);
我想检查一下这个 mat1
里面是不是只包含 1 和 0,也就是说里面可能有一些 1 和一些 0,或者全是 0,或者全是 1。
6 个回答
1
如果你知道它是整数类型,那么(令人惊讶的是)检查最大值和最小值会更快(即使不需要同时进行这两个操作):
In [11]: m = np.random.randint(0, 2, (10, 10))
In [12]: %timeit np.all((m == 0) | (m == 1))
10000 loops, best of 3: 33.7 µs per loop
In [13]: %timeit m.dtype == int and m.min() == 0 and m.max() == 1
10000 loops, best of 3: 29.8 µs per loop
In [21]: m = np.random.randint(0, 2, (10000, 10000))
In [22]: %timeit np.all((m == 0) | (m == 1))
1 loops, best of 3: 705 ms per loop
In [23]: %timeit m.dtype == int and m.min() == 0 and m.max() == 1
1 loops, best of 3: 481 ms per loop
1
你可以使用 unique
这个功能。
import numpy as np
mat1 = np.array([[1,0,1], [1,1,0], [0,0,0]])
np.unique(mat1)
# array([0, 1])
1 in np.unique(mat1)
# True
0 in np.unique(mat1)
# True
np.unique(mat1) == [0, 1]
# array([ True, True], dtype=bool)
你也可以使用 setdiff1d
这个功能。
np.setdiff1d(mat1, [0, 1])
# array([], dtype=int64)
np.setdiff1d(mat1, [0, 1]).size
# 0
2
简单来说:
In [6]:
set((mat1+mat2).ravel()).issubset(set((1,0)))
Out[6]:
True
In [7]:
mat3 = np.array([[0,5,0], [0,0,1], [1,1,1]])
set((mat1+mat3).ravel()).issubset(set((1,0)))
Out[7]:
False
4
- 检查所有元素是否都是 0:
np.all(mat == 0)
- 检查所有元素是否都是 1:
np.all(mat == 1)
- 检查是否有任何元素是 0:
np.any(mat == 0)
- 检查是否有任何元素是 1:
np.any(mat == 1)
>>> mat1 = np.array([[1,0,1], [1,1,0], [0,0,0]])
>>> mat2 = np.array([[0,1,0], [0,0,1], [1,1,1]])
>>> np.all(mat1 == 0)
False
>>> np.any(mat1 == 0)
True
>>> np.all(mat1 == 1)
False
>>> np.any(mat1 == 1)
True
>>> mat3 = mat1 + mat2
>>> mat3
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
>>> np.all(mat3 == 1)
True
更新
要检查数组中是否只包含 1
或 0
,没有其他值,可以使用以下代码:
>>> mat1 = np.array([[1,0,1], [1,1,0], [0,0,0]])
>>> mat2 = np.array([[0,1,2], [3,4,5], [6,7,8]])
>>> np.all((mat1 == 0) | (mat1 == 1))
True
>>> np.all((mat2 == 0) | (mat2 == 1))
False
2
这样怎么样:
>>> 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
>>>