在日常的科学计算中,我们经常需要使用逻辑运算符。numpy
作为python
的科学计算包,也为我们提供了相应的函数。例如logical_and
表示逻辑与
,而 bitwise_and
表示按位与
(也就是说该函数需要先把十进制的数字转换成二进制,然后按位操作)。然而在使用中有一个地方需要注意,那就是| 与 &
对于不同的数组类型代表的含义不同。
The & operator can be used as a shorthand for np.logical_and on boolean ndarrays. see bitwise_and
The & operator can be used as a shorthand for np.bitwise_and on ndarrays. see logical_and
注意:|
运算符也是同样,这里我们仅以&
举例:
>>> x1 = np.array([2, 5, 255])
>>> x2 = np.array([3, 14, 16])
>>> x1 & x2
array([ 2, 4, 16])
>>> a = np.array([True, False])
>>> b = np.array([False, False])
>>> a & b
array([False, False])
最后放一个1<x<4
的例子
>>> x = np.arange(5)
>>> np.logical_and(x>1, x<4)
array([False, False, True, True, False])
>>> (x>1) & (x<4)
array([False, False, True, True, False])
>>> x>1 & x<4 # 注意使用括号,不然报错
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
实际建议写logical_and
和bitwise_and
,避免理解上的困难。