📜  Python集 |对称差()

📅  最后修改于: 2022-05-13 01:54:44.855000             🧑  作者: Mango

Python集 |对称差()

Python Set 的这个内置函数帮助我们获得了两个集合之间的对称差异,它等于两个集合中的任何一个中存在的元素,但两个集合都不相同。让我们看一下两组之间 symmetric_difference 的维恩图。

对称差
对称差异标记为绿色

如果存在 set_A 和 set_B,那么它们之间的对称差将等于 set_A 和 set_B 的并集,而两者之间没有交集。

// Takes a single parameter that has to be 
// a set and returns a new set which is the 
// symmetric difference between the two sets.
set_A.symmetric_difference(set_B)

例子:

Input: set_A = {1, 2, 3, 4, 5}
       set_B = {6, 7, 3, 9, 4}
Output :  {1, 2, 5, 6, 7, 9}
Explanation: The common elements {3, 4} 
are discarded from the output.

Input:
set_A = {"ram", "rahim", "ajay", "rishav", "aakash"}
set_B = {"aakash", "ajay", "shyam", "ram", "ravi"}
Output: {"rahim", "rishav", "shyam", "ravi"}

Explanation: The common elements {"ram", "ajay", 
"aakash"} are discarded from the final set

在这个程序中,我们将尝试找到两个集合之间的对称差:

# Python code to find the symmetric_difference
# Use of symmetric_difference() method
  
set_A = {1, 2, 3, 4, 5}
set_B = {6, 7, 3, 9, 4}
print(set_A.symmetric_difference(set_B))

输出:

{1, 2, 5, 6, 7, 9}

还有另一种方法来获得两个集合之间的对称差,通过使用运算符“ ^ ”。
例子:

# Python code to find the Symmetric difference
# using ^ operator.
  
# Driver Code
set_A = {"ram", "rahim", "ajay", "rishav", "aakash"}
set_B = {"aakash", "ajay", "shyam", "ram", "ravi"}
print(set_A ^ set_B)

输出:

{'shyam', 'ravi', 'rahim', 'rishav'}
# One more example Python code to find 
# the symmetric_difference use of 
# symmetric_difference() method
  
A = {'p', 'a', 'w', 'a', 'n'}
B = {'r', 'a', 'o', 'n', 'e'}
C = {}
  
print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
  
print(A.symmetric_difference(C))
print(B.symmetric_difference(C))
  
# this example is contributed by sunny6041

输出:

set(['e', 'o', 'p', 'r', 'w'])
set(['e', 'o', 'p', 'r', 'w'])
set(['a', 'p', 'w', 'n'])
set(['a', 'r', 'e', 'o', 'n'])