在从http://www.learnpython.org/en/Sets学习Python时,我遇到了集合之间的symmetric_difference概念。 我认为它与集合上的“异或”操作产生相同的输出。 它有什么不同之处呢?
在从http://www.learnpython.org/en/Sets学习Python时,我遇到了集合之间的symmetric_difference概念。 我认为它与集合上的“异或”操作产生相同的输出。 它有什么不同之处呢?
没有什么区别。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实现确保你只处理集合,但除此之外没有区别。
是的,它们基本相同,只是XOR是布尔操作,而symmetric_difference
是集合操作。实际上,即使您链接的文档页面也表明了这一点:
要找出哪些成员仅参加了一个事件,请使用"symmetric_difference"方法
您还可以查看有关逻辑XOR和对称差异之间关系的更详细的数学解释。
^
异或运算符应用于一对集合时调用symmetric_difference
方法是非常合理的。 - PM 2Ring