Python中的isdisjoint()函数

在本文中,我们将学习如何在set()数据类型上实现isdisjoint()函数。此函数检查作为参数传递的集合是否具有任何共同的元素。如果找到任何元素,则返回False,否则返回True。

除了设置输入之外,isdisjoint()函数还可以将列表,元组和字典作为输入参数。THse类型由Python解释器隐式转换为集合类型。

语法

<set 1>.isdisjoint(<set 2>)

返回值

布尔值True / False

现在让我们考虑一个与实现有关的图示

示例

#declaration of the sample sets
set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = {'p','o','i','n','t'}
set_3 = {'p','y'}

#checking of disjoint of two sets
print("set1 and set2 are disjoint?", set_1.isdisjoint(set_2))
print("set2 and set3 are disjoint?", set_2.isdisjoint(set_3))
print("set1 and set3 are disjoint?", set_1.isdisjoint(set_3))

输出结果

set1 and set2 are disjoint? False
set2 and set3 are disjoint? False
set1 and set3 are disjoint? True

说明

由于set_1和set_2具有相同的元素,因此显示布尔值False。这与set_2和set_3之间的比较相同。但是在set_1和set_3之间的比较中,布尔值True会显示出来,因为找不到公共元素。

现在让我们看一下另一个涉及set类型之外的可迭代对象的图示。

注意:在外部声明的set_1必须是集合类型,以使解释器知道集合之间的比较。内部存在的参数可以是任何隐式转换为集合类型的类型。

示例

#declaration of the sample iterables
set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = ('p','o','i','n','t')
set_3 = {'p':'y'}
set_4 = ['t','u','t','o','r','i','a','l']

#checking of disjoint of two sets
print("set1 and set2 are disjoint?", set_1.isdisjoint(set_2))
print("set2 and set3 are disjoint?", set_1.isdisjoint(set_3))
print("set1 and set3 are disjoint?", set_1.isdisjoint(set_4))

输出结果

set1 and set2 are disjoint? False
set2 and set3 are disjoint? True
set1 and set3 are disjoint? False

在此还进行检查以找到共同的元素,并产生所需的输出。

结论

在本文中,我们学习了如何在Python中使用disjoint()函数以及借助该函数可以比较所有类型的参数。