4

有 "+=" 运算符,即 int。

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

是否有布尔的“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

但是,我经常做这个操作,我不认为它看起来很整洁。

谢谢

4

3 回答 3

10

是的 - 你可以使用&=.

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

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

应该注意(如下面的评论),这实际上是一个按位运算;当以布尔值开始时,它才会具有预期的行为a,并且操作仅使用布尔值执行。

于 2013-06-10T14:29:27.937 回答
4

nrpeterson showed you how to use &= with boolean.

I show only what can happend if you mix boolean and integer

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
于 2013-06-10T14:50:46.923 回答
3

您可以查看操作员库: http ://docs.python.org/3/library/operator.html

这可以让你做

a = True
a = operator.iand(a, 5>6) # a is False
于 2013-06-10T14:33:08.680 回答