簡體   English   中英

什么是Python symmetric_difference,它與XOR操作有什么不同?

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

http://www.learnpython.org/en/Sets學習Python時,我遇到了集合之間的symmetric_difference概念。 我認為它給出了與套裝上的“獨占或”操作相同的輸出。 它有什么不同?

沒有區別。 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實現確保您確實只處理集合,但是沒有區別。

是的,它幾乎是一樣的,只是XOR是對布爾值的操作,而symmetric_difference是對集合的操作。 實際上,即使您的鏈接文檔頁面也說明了這一點:

要找出哪些成員參加了其中一個事件,請使用“symmetric_difference”方法

您還可以看到關於邏輯XOR與集合上的對稱差異之間的關系的更詳細的數學解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM