Python 集合 isdisjoint() 方法



Python 集合的isdisjoint() 方法用于检查两个集合是否没有共同元素。如果两个集合是不相交的,即它们的交集为空,则返回 True,否则返回 False。

此方法可以用于任何可迭代对象,而不仅仅是集合。如果在另一个集合或可迭代对象中的任何元素在原始集合中找到,则 isdisjoint() 方法返回 False。否则,它返回 True。

语法

以下是 Python 集合isdisjoint() 方法的语法和参数:-

set1.isdisjoint(other)

参数

此方法接受另一个集合对象作为参数,将其与当前集合进行比较,以确定两者是否不相交。

返回值

此方法返回布尔值 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

isdisjoint() 方法可以与集合或其他数据类型(如列表、元组等)一起使用。在此示例中,我们将 isdisjoint() 方法应用于集合和列表:-

# 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.
python_set_methods.htm
广告

© . All rights reserved.