Boolean operators vs Bitwise operators

前端 未结 9 1438
孤街浪徒
孤街浪徒 2020-11-22 06:34

I am confused as to when I should use Boolean vs bitwise operators

  • and vs &
  • or vs |
9条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:26

    If you are trying to do element-wise boolean operations in numpy, the answer is somewhat different. You can use & and | for element-wise boolean operations, but and and or will return value error.

    To be on the safe side, you can use the numpy logic functions.

    np.array([True, False, True]) | np.array([True, False, False])
    # array([ True, False,  True], dtype=bool)
    
    np.array([True, False, True]) or np.array([True, False, False])
    # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    
    np.logical_or(np.array([True, False, True]), np.array([True, False, False]))
    # array([ True, False,  True], dtype=bool)
    

提交回复
热议问题