0

假设我有这个条件,假设 a 和 b 已经是布尔值

if not a and b:
    do something
if a and not b:
    do something different

有什么方法可以进一步优化它,还有更多的pythonic方式来处理这个吗?

4

2 回答 2

4

两种情况相互排斥。您可以将其重写为:

if bool(a) != bool(b): # a xor b
    if a:
        print "a and not b"
    else:
        print "not a and b"

但它看起来更加模糊。所以对我来说最好的方法是:

if not a and b:
  print "not a and b"
elif a and not b:
  print "a and not b"

(注意elif而不是if)。

于 2012-08-12T14:23:42.700 回答
-1

好像您正在寻找一个异或(xor)。试试这个:

if a is not b:
    print "a xor b"
于 2012-08-12T14:21:26.113 回答