在从http://www.learnpython.org/en/Sets学习 Python 时,我遇到了集合之间 symmetric_difference 的概念。我认为它给出的输出与集合上的“异或”操作相同。它有什么不同?
问问题
4236 次
2 回答
3
没有区别。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 实现确保您确实只在集合上工作,但除此之外没有区别。
于 2015-08-31T11:54:52.533 回答
1
是的,它几乎相同,只是 XOR 是对布尔值的操作,并且symmetric_difference
是对集合的操作。实际上,即使您的链接文档页面也这样说:
要找出哪些成员只参加了其中一项活动,请使用“symmetric_difference”方法
您还可以看到有关逻辑 XOR 和集合上的对称差异之间关系的更详细的数学解释。
于 2015-08-31T11:57:56.873 回答