Python与XOR操作的区别是什么?

Python与XOR操作的区别是什么?,python,set,xor,symmetric-difference,Python,Set,Xor,Symmetric Difference,在学习Python的过程中,我遇到了集合之间的对称差异的概念。 我认为它的输出与集合上的“异或”操作相同。 有什么不同吗?没有区别。XORing集合通过调用symmetric_difference函数来工作。这是在sets.py中实现的集合: def __xor__(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in e

在学习Python的过程中,我遇到了集合之间的对称差异的概念。 我认为它的输出与集合上的“异或”操作相同。
有什么不同吗?

没有区别。XORing集合通过调用
symmetric_difference
函数来工作。这是在sets.py中实现的集合:

def __xor__(self, other):
    """Return the symmetric difference of two sets as a new set.

    (I.e. all elements that are in exactly one of the sets.)
    """
    if not isinstance(other, BaseSet):
        return NotImplemented
    return self.symmetric_difference(other)

def symmetric_difference(self, other):
    """Return the symmetric difference of two sets as a new set.

    (I.e. all elements that are in exactly one of the sets.)
    """
    result = self.__class__()
    data = result._data
    value = True
    selfdata = self._data
    try:
        otherdata = other._data
    except AttributeError:
        otherdata = Set(other)._data
    for elt in ifilterfalse(otherdata.__contains__, selfdata):
        data[elt] = value
    for elt in ifilterfalse(selfdata.__contains__, otherdata):
        data[elt] = value
    return result

正如您所看到的,XOR实现确保您确实只处理集合,但在其他方面没有差异。

是的,这几乎是一样的,只是XOR是布尔运算,
symmetric_difference
是集合运算。实际上,即使是链接的文档页面也会这样说:

要了解哪些成员只参加了一次活动,请使用“对称差异”方法


你也可以看到逻辑异或和集合上的对称差之间的关系。

好吧,它们不是完全相同的东西,它们是同构运算(正如你链接中的公认答案所讨论的),但是Python重载
^
exclusive\u或操作符调用
symmetric\u difference
方法(当它应用于一对集合时)是非常有意义的。