了解 np.bitwise_and 的行为

Understanding the behavior of np.bitwise_and

考虑以下示例代码:

rand2 = np.random.rand(10)
rand1 = np.random.rand(10)
rand_bool = np.asarray([True, False, True, True, False, True, True, False, False, True], dtype=np.bool)
a = np.bitwise_and(rand1 > .2, rand2 < .9, rand_bool)
print(a)
b = np.bitwise_and(rand1 < .2, rand2 > .9, rand_bool)
print(a)

我电脑上的输出(Python 3.4)是:

[ True False  True  True  True False  True  True  True  True]
[False False False False False False False False False False]

我不明白为什么将另一个 bitwise_and 分配给变量 b 会更改变量 a。又是一个测试a is breturnsTrue。谁能向我解释这种行为?非常感谢!

bitwise_and的第三个参数是可选的。它指定用于存储结果的输出数组。给定的时候也是bitwise_and的return值。您在 bitwise_and 的两次调用中使用了相同的数组 rand_bool,因此它们都将结果写入该数组并 returning 该值。

换句话说,您的代码等同于:

rand_bool[:] = np.bitwise_and(rand1 > .2, rand2 < .9)  # Put the result in rand_bool
a = rand_bool   # Assign a to rand_bool

rand_bool[:] = np.bitwise_and(rand1 > .2, rand2 < .9)  # Put the result in rand_bool
b = rand_bool   # Assign b to rand_bool