當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Set difference()用法及代碼示例


Python中兩個集合之間的差異等於兩個集合中元素數量之間的差異。函數difference()返回的集合是兩個集合之間的差。讓我們嘗試找出兩個集合A和B之間的區別。然後(集合A-集合B)將是集合A中的元素,但不是集合B中的(集合B-集合A)將是存在的元素在集合B中,但不在集合A中。
例:

set A = {10, 20, 30, 40, 80}
set B = {100, 30, 80, 40, 60}

set A - set B = {10, 20}
set B - set A = {100, 60}

Explanation:A - B is equal to the elements present in A but not in B
             B - A is equal to the elements present in B but not in A

讓我們看一下以下差異集函數的維恩圖。

set-difference


用法:

set_A.difference(set_B) for (A - B)
set _B.difference(set_A) for (B - A)

在此程序中,我們將嘗試通過兩種方式找出兩個集合set_A和set_B之間的差異:

# Python code to get the difference between two sets 
# using difference() between set A and set B 
  
# Driver Code 
A = {10, 20, 30, 40, 80} 
B = {100, 30, 80, 40, 60} 
print (A.difference(B)) 
print (B.difference(A))
輸出:
{10, 20}
{100, 60}

我們還可以使用-運算符查找兩組之間的差異。

# Python code to get the difference between two sets 
# using difference() between set A and set B 
  
# Driver Code 
A = {10, 20, 30, 40, 80} 
B = {100, 30, 80, 40, 60} 
print (A - B) 
print (B - A)
輸出:
{10, 20}
{100, 60}


相關用法


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