Python 中的 isdisjoint() 函数
在本文中,我们学习如何针对 set() 数据类型实现 isdisjoint() 函数。此函数检查作为参数传入的集合中是否有任何常见元素。如果找到任何元素,则返回 False,否则返回 True。
除了 set 输入,isdisjoint() 函数还可以将列表、元组和字典作为输入参数。Python 解释器会将这些类型隐式转换为 set 类型。
语法
<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 必须是 set 类型,以使解释器了解集合之间的比较。内部传入的参数可以是任何类型,这些类型将隐式转换为 set 类型。
示例
#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() 函数,以及该函数允许比较哪些类型的参数。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP