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
廣告