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_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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。