考虑以下示例代码:
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)我的计算机上的输出(Python3.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 b返回True。有人能向我解释一下这种行为吗?非常感谢!
发布于 2015-08-11 10:58:35
bitwise_and的第三个参数是可选的。它指定要存储结果的输出数组。当给出它时,它也是bitwise_and的返回值。您在两个bitwise_and调用中都使用了相同的数组rand_bool,因此它们都在将结果写入该数组并返回该值。
换句话说,您的代码相当于:
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_boolhttps://stackoverflow.com/questions/31939799
复制相似问题