【问题标题】:Is there a "and=" operator for boolean?布尔值是否有“and=”运算符?
【发布时间】:2013-06-06 05:57:07
【问题描述】:

有“+=”操作符,即int。

a = 5
a += 1
b = a == 6 # b is True

bool 是否有“and=" 运算符?

a = True
a and= 5 > 6 # a is False
a and= 5 > 4 # a is still False

我知道,这个 'and=' 运算符对应于:

a = True
a = a and 5 > 6 # a is False
a = a and 5 > 4 # a is still False

但是,我经常做这个操作,我觉得它看起来不太整洁。

谢谢

【问题讨论】:

  • 你的意思是只有10值,那将是按位and

标签: python boolean operators


【解决方案1】:

是的 - 你可以使用&=

a = True
a &= False  # a is now False
a &= True   # a is still False

您可以类似地使用|= 表示“或=”。

应该注意(如下面的 cmets 所示)这实际上是按位运算; 如果a 以布尔值开始,并且操作仅使用布尔值执行,它将具有预期的行为。

【讨论】:

  • 这是当前语言中最接近的值,但并不完全符合要求:这些运算符执行 bitwise and and or。当两边的值不是严格的布尔值时,差异很重要。
  • &=是按位运算,但问题是要求布尔运算,你应该指出区别。
  • 要使用它来代替and=,只需将任何非布尔操作数包装在bool() 中,这实际上是常规and 所做的。
【解决方案2】:

nrpeterson 向您展示了如何将 &= 与布尔值一起使用。

我只展示了混合布尔值和整数会发生什么

a = True
a &= 0 # a is 0
if a == False : print "hello" # "hello"

a = True
a &= 1 # a is 1
if a == False : print "hello" # nothing

a = True
a &= 2 # a is 0 (again)
if a == False : print "hello" # "hello"

a = True
a &= 3 # a is 1
if a == False : print "hello" # nothing

【讨论】:

    【解决方案3】:

    您可以查看运算符库: http://docs.python.org/3/library/operator.html

    这可以让你做

    a = True
    a = operator.iand(a, 5>6) # a is False
    

    【讨论】:

    • 很高兴知道这存在于operator 模块中,但在大多数情况下它没有用
    • 此外,它也是按位的。
    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2013-03-02
    • 2012-09-20
    • 2014-05-31
    相关资源
    最近更新 更多