Python 布尔运算符与位运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3845018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:00:30  来源:igfitidea点击:

Boolean operators vs Bitwise operators

pythonbitwise-operatorsboolean-operations

提问by Jiew Meng

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

我对什么时候应该使用布尔运算符和按位运算符感到困惑

  • andvs &
  • orvs |
  • and对比 &
  • or对比 |

Could someone enlighten me as to when do i use each and when will using one over the other affect my results?

有人能告诉我什么时候使用每一种以及何时使用一种会影响我的结果吗?

采纳答案by Mark Byers

Here are a couple of guidelines:

以下是一些指导方针:

  • Boolean operators are usually used on booleanvalues but bitwise operators are usually used on integervalues.
  • Boolean operators are short-circuitingbut bitwise operators are notshort-circuiting.
  • 布尔运算符通常用于布尔值,但按位运算符通常用于数值。
  • 布尔运算符是短路的,但按位运算符不是短路的。

The short-circuiting behaviour is useful in expressions like this:

短路行为在这样的表达式中很有用:

if x is not None and x.foo == 42:
    # ...

This would not work correctly with the bitwise &operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly ordoes not evaluate the second argument if the first is True.

这对于按位运算&符将无法正常工作,因为总是会评估双方,给出AttributeError: 'NoneType' object has no attribute 'foo'. 当您使用布尔and运算符时,当第一个表达式为 False 时,不会计算第二个表达式。同样or,如果第一个参数为 True,则不会评估第二个参数。

回答by pyfunc

Boolean operation are logical operations.

布尔运算是逻辑运算。

Bitwise operations are operations on binary bits.

按位运算是对二进制位的运算。

Bitwise operations:

按位运算:

>>> k = 1
>>> z = 3
>>> k & z  
1
>>> k | z  
3

The operations:

操作:

And & 1 if both bits are 1, 0 otherwise
Or  | 1 if either bit is 1
Xor ^ 1 if the bits are different, 0 if they're the same
Not ~ Flip each bit

Some of the uses of bitwise operations:

按位运算的一些用途:

1) Setting and Clearing Bits

1) 设置和清除位

Boolean operations:

布尔运算:

>>> k = True
>>> z = False
>>> k & z  # and
False
>>> k | z  # or
True
>>> 

回答by Tendayi Mawushe

The hint is in the name:

提示在名称中:

  • Boolean operators are for performing logical operations(truth testing common in programming and formal logic)
  • Bitwise operators are for "bit-twiddling"(low level manipulation of bits in byte and numeric data types)
  • 布尔运算符用于执行逻辑运算(编程和形式逻辑中常见的真值测试)
  • 按位运算符用于“位旋转”(字节和数字数据类型中位的低级操作)

While it is possible and indeed sometimes desirable (typically for efficiency reasons) to perform logical operations with bitwise operators, you should generally avoid them for such purposes to prevent subtle bugs and unwanted side effects.

虽然使用按位运算符执行逻辑运算是可能的,而且有时确实是可取的(通常是出于效率原因),但您通常应避免出于此类目的使用它们,以防止出现细微的错误和不需要的副作用。

If you need to manipulate bits, then the bitwise operators are purpose built. The fun book: Hackers Delightcontains some cool and genuinely useful examples of what can be achieved with bit-twiddling.

如果您需要操作位,那么按位运算符是专门构建的。有趣的书:Hackers Delight包含一些很酷且真正有用的示例,说明可以通过 bit-twiddling 实现什么。

回答by Tendayi Mawushe

In theory, andand orcome straight from boolean logic (and therefore operate on two booleans to produce a boolean), while &and |apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly.

从理论上讲,andor直接从布尔逻辑来(并且因此在两个布尔操作以产生一个布尔),而&|布尔应用和/或整数的各个位。这里有很多关于后者如何工作的问题。

Here are practical differences that potentially affect your results:

以下是可能影响您的结果的实际差异:

  1. andand orshort-circuiting, i.e. True or sys.exit(1)will not exit, because for a certain value (True or ..., False and ...) of the first operand, the second one wouldn't change the result = does not need to be evaluated. But |and &don't short-circuit - True | sys.exit(1)throws you outta the REPL.
  2. (Only applies to some? languages with operator overloading, including Python:) &and |are regular operators and can be overloaded - andand orare forged into the language (although at least in Python, the special method for coercion to boolean may have side effects).
  3. (only applies to a few languages [see KennyTM's comment]:) andand orreturn (always? never really understand this, nor did I need it) the value of an operand instead of Trueor False. This doesn't change the meaning of boolean expressions in conditions - 1 or Trueis 1, but 1is true, too. But it was once used to emulate a conditional operator (cond ? true_val : false_valin C syntax, true_val if cond else false_valin Python since a few years). For &and |, the result type depends on how the operands overload the respective special methods (True & Falseis False, 99 & 7is 3, for sets it's unions/intersection...).
  1. andor短路,即True or sys.exit(1)不会退出,因为对于第一个操作数的某个值 ( True or ..., False and ...),第二个不会改变结果 = 不需要评估。不过|&不短路-True | sys.exit(1)抛出你离开的REPL。
  2. (仅适用于某些?带有运算符重载的语言,包括 Python:)&并且|是常规运算符并且可以重载 -and并且or被伪造到语言中(尽管至少在 Python 中,强制转换为布尔值的特殊方法可能有副作用)。
  3. (仅适用于几种语言 [参见 KennyTM 的评论]:)andor返回(总是?从来没有真正理解这一点,我也不需要它)操作数的值而不是Trueor False。这不会改变条件中布尔表达式的含义 - 1 or Trueis 1,但1也是 true 。但它曾经被用来模拟条件运算符(cond ? true_val : false_val在 C 语法中,true_val if cond else false_val几年后在 Python 中)。对于&and |,结果类型取决于操作数如何重载各自的特殊方法(True & Falseis False99 & 7is 3,对于集合,它是联合/交集......)。

But even when e.g. a_boolean & another_booleanwould work identically, the right solution is using and- simply because andand orare associated with boolean expression and condition while &and |stand for bit twiddling.

但即使当 ega_boolean & another_boolean工作相同时,正确的解决方案是使用and- 仅仅因为andandor与布尔表达式和条件相关联,而 while&|代表位旋转。

回答by Arend

Here's a further difference, which had me puzzled for a while just now: because &(and other bitwise operators) have a higher precedence than and(and other boolean operators) the following expressions evaluate to different values:

这是一个进一步的差异,刚才让我困惑了一段时间:因为&(和其他按位运算符)比and(和其他布尔运算符)具有更高的优先级,因此以下表达式评估为不同的值:

0 < 1 & 0 < 2

versus

相对

0 < 1 and 0 < 2

To wit, the first yields Falseas it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.

也就是说,第一个产生,False因为它等价于0 < (1 & 0) < 2,因此0 < 0 < 2,因此0 < 0 and 0 < 2

回答by C8H10N4O2

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 andand orwill return value error.

如果您尝试在 中进行元素级布尔运算numpy,答案会有所不同。您可以将&and|用于逐元素布尔运算,但andandor将返回值错误。

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

为了安全起见,您可以使用numpy 逻辑函数

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)

回答by Geoff Langenderfer

Boolean 'and' vs. Bitwise '&':

布尔“与”与按位“&”:

Pseudo-code/Python helped me understand the difference between these:

伪代码/Python 帮助我理解了这些之间的区别:

def boolAnd(A, B):
    # boolean 'and' returns either A or B
    if A == False:
        return A
    else:
        return B

def bitwiseAnd(A , B):
    # binary representation (e.g. 9 is '1001', 1 is '0001', etc.)

    binA = binary(A)
    binB = binary(B)



    # perform boolean 'and' on each pair of binaries in (A, B)
    # then return the result:
    # equivalent to: return ''.join([x*y for (x,y) in zip(binA, binB)])

    # assuming binA and binB are the same length
    result = []
    for i in range(len(binA)):
      compar = boolAnd(binA[i], binB[i]) 
      result.append(compar)

    # we want to return a string of 1s and 0s, not a list

    return ''.join(result)

回答by CristiFati

The general rule is to use the appropriate operator for the existing operands. Use boolean (logical) operators with boolean operands, and bitwise operators with (wider) integral operands (note: Falseis equivalent to 0, and Trueto 1). The only "tricky" scenario is applying boolean operators to non boolean operands.
Let's take a simple example, as described in [SO]: Python - Differences between 'and' and '&' [duplicate]: 5 & 7vs.5 and 7.

一般规则是对现有操作数使用适当的运算符。对布尔操作数使用布尔(逻辑)运算符,对(更宽的)整数操作数使用按位运算符(注意:False等价于0True等价于1)。唯一的“棘手”场景是将布尔运算符应用于非布尔操作数。
让我们举一个简单的例子,如[SO]: Python - 'and' 和 '&' 之间的差异 [重复]: 5 & 7vs.5 and 7.

For the bitwise and(&), things are pretty straightforward:

对于按位( &),事情非常简单:

5     = 0b101
7     = 0b111
-----------------
5 & 7 = 0b101 = 5
5     = 0b101
7     = 0b111
-----------------
5 & 7 = 0b101 = 5

For the logical and, here's what [Python 3]: Boolean operationsstates (emphasisis mine):

对于逻辑,这里是[Python 3]:布尔运算状态(重点是我的):

(Note that neither andnor orrestrict the value and type they return to Falseand True, but rather return the last evaluated argument.

(请注意,无论是也不限制值并键入他们返回,而是返回最后一个变量

Example:

示例

>>> 5 and 7
7
>>> 7 and 5
5
>>> 5 and 7
7
>>> 7 and 5
5

Of course, the same applies for |vs.or.

当然,这同样适用于| .

回答by pooria

Logical Operations

逻辑运算

are usually used for conditional statements. For example:

通常用于条件语句。例如:

if a==2 and b >10 then /*Do something...*/ endif It means if both conditions((a==2) (b>10)) are true at the same time then conditional statement body can be executed.

if a==2 and b >10 then /*Do something...*/ endif 这意味着如果两个条件((a==2) (b>10)) 同时为真,则可以执行条件语句体。

Bitwise Operations

按位运算

Bitwise operations can be used for data manipulation and extraction. For example, if you want to extract four LSB(Least Significant Bits) of an integer, you can do this:

按位运算可用于数据操作和提取。例如,如果你想提取一个整数的四个 LSB(最低有效位),你可以这样做:

Extraction:

萃取:

poo & 0x000F

poo & 0x000F

Masking:

掩蔽:

poo | 0xFFF0

poo | 0xFFF0