代码之家  ›  专栏  ›  技术社区  ›  Chris

了解np.bitwise_and的行为

  •  0
  • Chris  · 技术社区  · 10 年前

    考虑以下示例代码:

    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 b 回报 True 有人能向我解释一下这种行为吗?谢谢!

    1 回复  |  直到 10 年前
        1
  •  2
  •   Warren Weckesser    10 年前

    的第三个论点 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_bool