📜  Python中的 isdisjoint()函数

📅  最后修改于: 2022-05-13 01:55:44.837000             🧑  作者: Mango

Python中的 isdisjoint()函数

Python set isdisjoint()函数检查两个集合是否不相交,如果不相交则返回True,否则返回False。当两个集合的交集为空时,我们称这两个集合是不相交的。简而言之,它们之间没有任何共同的元素。

例子:

Let set A = {2, 4, 5, 6}
and set B = {7, 8, 9, 10} 

集合 A 和集合 B 被称为不相交集合,因为它们的交集为空。它们之间没有任何共同的元素。

Python isdisjoint()语法

Python isdisjoint()参数

isdisjoint() Python方法只接受一个参数。它还可以将可迭代的(列表、元组、字典和字符串)用于 disjoint()。 isdisjoint() 方法会自动将可迭代对象转换为集合,并检查集合是否不相交。

Python isdisjoint()返回值

Python设置 isdisjoint() 示例

示例 1:工作集 isdisjoin()

Python3
# Python3 program for isdisjoint() function
set1 = {2, 4, 5, 6}
set2 = {7, 8, 9, 10}
set3 = {1, 2}
 
# checking of disjoint of two sets
print("set1 and set2 are disjoint?",
      set1.isdisjoint(set2))
 
print("set1 and set3 are disjoint?",
      set1.isdisjoint(set3))


Python3
# Set
A = {2, 4, 5, 6}
 
# List
lis = [1, 2, 3, 4, 5]
 
# Dictionary dict, Set is formed on Keys
dict = {1: 'Apple', 2: 'Orage'}
 
# Dictionary dict2
dict2 = {'Apple': 1, 'Orage': 2}
 
print("Set A and List lis disjoint?", A.isdisjoint(lis))
print("Set A and dict are disjoint?", A.isdisjoint(dict))
print("Set A and dict2 are disjoint?", A.isdisjoint(dict2))


输出:

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

示例 2: Python isdisjoint() 与其他 Iterables 作为参数

Python3

# Set
A = {2, 4, 5, 6}
 
# List
lis = [1, 2, 3, 4, 5]
 
# Dictionary dict, Set is formed on Keys
dict = {1: 'Apple', 2: 'Orage'}
 
# Dictionary dict2
dict2 = {'Apple': 1, 'Orage': 2}
 
print("Set A and List lis disjoint?", A.isdisjoint(lis))
print("Set A and dict are disjoint?", A.isdisjoint(dict))
print("Set A and dict2 are disjoint?", A.isdisjoint(dict2))

输出:

Set A and List lis disjoint? False
Set A and dict are disjoint? False
Set A and dict2 are disjoint? True