📜  Python集 |不同之处()

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

Python集 |不同之处()

Python中两个集合的差等于两个集合中元素个数的差。函数diff()返回一个集合,它是两个集合之间的差。让我们试着找出两个集合 A 和 B 之间的区别。那么 (set A – set B) 将是存在于集合 A 但不在 B 中的元素,并且 (set B – set 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_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}

如果我们有相等的集合,那么它将返回空集合。

# 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 = {10, 20, 30, 40, 80, 100}
print (A - B)
输出:
set()