在从http://www.learnpython.org/en/Sets学习Python时,我遇到了集合之间的symmetric_difference的概念。我认为它给出的输出与集合上的“异或”操作相同。它有什么不同?
发布于 2015-08-31 19:54:53
这是没有区别的。XORing sets通过调用symmetric_difference函数工作。这来自于sets.py中sets的实现:
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实现确保您确实只处理集合,但除此之外没有区别。
发布于 2015-08-31 19:57:57
是的,它几乎是一样的,只是异或是一种对布尔值的操作,而symmetric_difference是一种对集合的操作。实际上,就连你的链接文档页面也是这样说的:
要找出哪些成员只参加了一个事件,请使用"symmetric_difference“方法
您还可以查看有关集合上的逻辑异或和对称差之间关系的this more detailed mathematical explanation。
https://stackoverflow.com/questions/32310533
复制相似问题