Tutorial Study Image

Python isdisjoint()

Python 中的 isdisjoint() 函数用于检查给定的两个集合是否不相交。如果集合不相交则返回 True,否则返回 False。不相交意味着两个集合没有共同的元素。


set_a.isdisjoint(set_b) #where parameter may be list, tuple, dictionary, and string
 

isdisjoint() 参数

isdisjoint() 函数接受一个参数。该方法会自动将给定的可迭代参数转换为一个集合,以检查其是否不相交。

参数 描述 必需/可选
set(集合) 要在其中搜索相同项的集合 必需

isdisjoint() 返回值

此方法返回一个布尔值 True 或 False。我们也可以说,如果两个集合的交集是空集,那么它们就是不相交集合。

输入 返回值
如果集合不相交 True
如果集合不相交 False

Python 中 isdisjoint() 方法的示例

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


A = {'a', 'b', 'c', 'd'}
B = {'e', 'f', 'g'}
C = {'b', 'h', 'i'}

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

输出


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

示例 2:isdisjoint() 与其他可迭代对象作为参数的工作方式


A = {1, 2, 3, 4}
B = [5, 3, 6]
C = '3mn7'
D ={1 : 'a', 2 : 'b'}
E ={'a' : 1, 'b' : 2}

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

输出


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