首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是Python,它与symmetric_difference有什么不同?

什么是Python,它与symmetric_difference有什么不同?
EN

Stack Overflow用户
提问于 2015-08-31 19:47:52
回答 2查看 4.2K关注 0票数 4

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

EN

回答 2

Stack Overflow用户

发布于 2015-08-31 19:54:53

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

代码语言:javascript
复制
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实现确保您确实只处理集合,但除此之外没有区别。

票数 3
EN

Stack Overflow用户

发布于 2015-08-31 19:57:57

是的,它几乎是一样的,只是异或是一种对布尔值的操作,而symmetric_difference是一种对集合的操作。实际上,就连你的链接文档页面也是这样说的:

要找出哪些成员只参加了一个事件,请使用"symmetric_difference“方法

您还可以查看有关集合上的逻辑异或和对称差之间关系的this more detailed mathematical explanation

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32310533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档