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'])
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Python Set | symmetric_difference()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。