如果两个集合之间没有任何共同项(即它们不相交),则 isdisjoint()
方法返回 True
。否则返回 False
。
示例
A = {1, 2, 3, }
B = {4, 5, 6}
# checks if set A and set B are disjoint
print(A.isdisjoint(B))
# Output: True
isdisjoint() 语法
isdisjoint()
方法的语法是
A.isdisjoint(B)
这里,A 和 B 是两个集合。
isdisjoint() 参数
isdisjoint()
方法接受一个参数
- B - 一个与集合 A 执行不相交操作的集合
我们还可以传递可迭代对象,例如列表、元组、字典或字符串。在这种情况下,isdisjoint()
首先将可迭代对象转换为集合,然后检查它们是否不相交。
isdisjoint() 返回值
isdisjoint()
方法返回
- 如果集合 A 和集合 B 不相交,则返回
True
- 如果集合 A 和集合 B 不相交,则返回
False
示例 1:Python 集合 disjoint()
A = {1, 2, 3}
B = {4, 5, 6}
C = {6, 7, 8}
print('A and B are disjoint:', A.isdisjoint(B))
print('B and C are disjoint:', B.isdisjoint(C))
输出
A and B are disjoint: True B and C are disjoint: False
在上面的示例中,我们使用 isdisjoint()
来检查集合 A、B 和 C 是否彼此不相交。
集合 A 和 B 彼此不相交,因为它们没有任何共同项。因此,它返回 True
。集合 B 和 C 有一个共同项 6。所以该方法返回 False
。
示例 2:isdisjoint() 与其他可迭代对象作为参数
# create a set A
A = {'a', 'e', 'i', 'o', 'u'}
# create a list B
B = ['d', 'e', 'f']
# create two dictionaries C and D
C = {1 : 'a', 2 : 'b'}
D = {'a' : 1, 'b' : 2}
# isdisjoint() with set and list
print('A and B are disjoint:', A.isdisjoint(B))
# isdisjoint() with set and dictionaries
print('A and C are disjoint:', A.isdisjoint(C))
print('A and D are disjoint:', A.isdisjoint(D))
输出
A and B are disjoint: False A and C are disjoint: True A and D are disjoint: False
在上面的示例中,我们传递了列表和字典作为 isdisjoint()
方法的参数。集合 A 和列表 B 有一个共同项 'a'
,所以它们不是不相交的集合。
集合 A 中的项 'a'
和字典 D
的键 'a'
是共同的。所以它们不是不相交的集合。
然而,A 和字典 D 是不相交的,因为字典的值不与集合项进行比较。
另请阅读