什么是Python的symmetric_difference,它与XOR操作有何不同?

4

在从http://www.learnpython.org/en/Sets学习Python时,我遇到了集合之间的symmetric_difference概念。 我认为它与集合上的“异或”操作产生相同的输出。 它有什么不同之处呢?

2个回答

3

没有什么区别。XOR集合的工作是通过调用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实现确保你只处理集合,但除此之外没有区别。


1

2
它们并不是完全相同的东西,它们是同构操作(如您链接中所讨论的那样),但当Python重载^异或运算符应用于一对集合时调用symmetric_difference方法是非常合理的。 - PM 2Ring
1
我稍微澄清了一下。 - mik01aj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接