简体   繁体   中英

What is Python symmetric_difference and how is it different from XOR operation?

While learning Python from http://www.learnpython.org/en/Sets I encountered the notion of symmetric_difference between sets. I thought it gave the same output as 'exclusive or' operations on sets. How is it different?

There is no difference. XORing sets works by calling the symmetric_difference function. This is from the implementation of sets in 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

As you can see the XOR implementation makes sure that you are indeed working on sets only, but otherwise there are no differences.

Yes, it is pretty much the same, just XOR is an operation on booleans, and symmetric_difference is an operation on sets. Actually, even your linked documentation page says this:

To find out which members attended only one of the events, use the "symmetric_difference" method

You can also see this more detailed mathematical explanation about relationship between logical XOR and symmetric difference on sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM