📜  Python Set isdisjoint()

📅  最后修改于: 2020-09-20 05:04:47             🧑  作者: Mango

如果两个集合是不相交的集,则isdisjoint()方法将返回True。如果不是,则返回False。

如果没有公共元素,则将两个集合称为不交集。例如:

A = {1, 5, 9, 0}
B = {2, 4, -5}

在此,集合AB是不相交的集合。

isdisjoint()的语法为:

set_a.isdisjoint(set_b)

isdisjoint()参数

isdisjoint()方法采用单个参数(一组)。

您还可以将一个可迭代的(列表,元组,字典和字符串)传递给disjoint()isdisjoint()方法将自动将可迭代对象转换为set,并检查这些set是否不相交。

从isdisjoint()返回值

isdisjoint()方法返回

  1. True如果两个集合是不相交的集合(如果set_aset_b是在上面的语法不相交的集合)
  2. 如果两个集合不是不相交的集合,则为False

示例1:isdisjoint()如何工作?

A = {1, 2, 3, 4}
B = {5, 6, 7}
C = {4, 5, 6}

print('Are A and B disjoint?', A.isdisjoint(B))
print('Are A and C disjoint?', A.isdisjoint(C))

输出

Are A and B disjoint? True
Are A and C disjoint? False

示例2:将isItjoint()与其他Iterables作为参数

A = {'a', 'b', 'c', 'd'}
B = ['b', 'e', 'f']
C = '5de4'
D ={1 : 'a', 2 : 'b'}
E ={'a' : 1, 'b' : 2}

print('Are A and B disjoint?', A.isdisjoint(B))
print('Are A and C disjoint?', A.isdisjoint(C))
print('Are A and D disjoint?', A.isdisjoint(D))
print('Are A and E disjoint?', A.isdisjoint(E))

输出

Are A and B disjoint? False
Are A and C disjoint? False
Are A and D disjoint? True
Are A and E disjoint? False