Python Set isdisjoint() 方法用于检查两个集合是否没有共同的元素。如果集合不相交,则返回 True,这意味着它们的交集为空,否则返回 False。
此方法可以用于任何可迭代对象,而不仅仅是集合。如果在原始集中找到另一个集合或可迭代对象中的任何元素,则 isdisjoint() 方法返回 False。否则,它将返回 True。
语法
以下是 Python Set isdisjoint() 方法的语法和参数 -
set1.isdisjoint(other)
参数
此方法接受另一个 set 对象作为参数,以将其与当前 set 进行比较,以确定两者是否不相交。
返回值
此方法将布尔值返回为 True 或 False。
示例 1
下面是一个基本示例,它显示了 isdisjoint() 方法的用法,其中包含两个没有共同元素的集合 -
# Define two sets
set1 = {1, 2, 3}
set2 = {4, 5, 6}
# Check if the sets are disjoint
print(set1.isdisjoint(set2))
输出
True
示例 2
在此示例中,我们展示了 isdisjoint() 方法如何处理具有公共元素的两个集合 -
# Define two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Check if the sets are disjoint
print(set1.isdisjoint(set2))
输出
False
示例 3
disjoint() 方法可以与集合或其他数据类型(如列表、元组等)一起使用。在这个例子中,我们在一个集合和一个列表上应用了 disjoint() 方法 -
# Define a set and a list
my_set = {1, 2, 3}
my_list = [4, 5, 6]
# Check if the set and the list are disjoint
print(my_set.isdisjoint(my_list))
输出
True
示例 4
此示例显示了如何在条件语句中使用 isdisjoint() 方法,以根据集合是否不相交来执行操作 -
# Define two sets
set1 = {1, 2, 3}
set2 = {4, 5, 6}
# Perform an action based on whether the sets are disjoint
if set1.isdisjoint(set2):
print("The sets have no common elements.")
else:
print("The sets have common elements.")
输出
The sets have no common elements.