使用Python编写布尔表达式

时间:2016-07-18 18:50:11

标签: python boolean-logic boolean-expression

我试图在Python中编写一个布尔表达式,但看起来Python只能通过位操作来执行XOR表达式。

在没有XOR运算符的情况下,在Python中编写此表达式的最佳方法是什么。

var collection = db.collection('user');

// Peform a distinct query against the userId field
collection.distinct('userId', function(err, result) {
    if (err) {
        throw err;
        return res.status(400).send(err);
    }
    console.log(result);
    return res.status(200).send(result);
});

编辑:

我试过这个:

(A ^ B ^ C ^ D) U ((B U C U D)' XOR A)

我希望简化它。

2 个答案:

答案 0 :(得分:3)

只需使用按位^运算符即可。当^ - 编辑在一起时,Python的布尔值会返回一个布尔值:

>>> True ^ True
False
>>> True ^ False
True

andor运算符主要用于支持短路,但XOR不能短路。

还有!=

>>> True != True
False
>>> True != False
True

但是当用更多参数链接时,这不符合您的要求:

>>> True != True != True
False

答案 1 :(得分:1)

(A and B and C and D) or ((A and not (B or C or D)) or (not A and (B and C and D)))将简化为: (B and C and D) or (A and not (B or C or D))