python 中的isdisjoint()
函數有助于檢查給定的兩個集合是否不相交。如果集合不相交,則返回真,否則返回假。不相交意味著這兩個集合沒有共同的元素。
**set_a.isdisjoint(set_b)** #where parameter may be list, tuple, dictionary, and string
isdisjoint()
參數:
isdisjoint()
函數接受一個參數。這個方法會自動將給定的可迭代參數轉換成一個集合,以檢查它是否不相交。
參數 | 描述 | 必需/可選 |
---|---|---|
設置 | 要在其中搜索相等項目的集合 | 需要 |
isdisjoint()
返回值
此方法返回一個布爾值 true 或 false。我們也可以說,如果兩個集合的交集是一個空集,它將是一個不相交的集合。
| 投入 | 返回值 | | 如果集合不相交 | 真實的 | | 如果集合不是不相交的 | 錯誤的 |
Python 中isdisjoint()
方法的示例
示例isdisjoint()
在 Python 中是如何工作的?
A = {'a', 'b', 'c', 'd'}
B = {'e', 'f', 'g'}
C = {'b', 'h', 'i'}
print(' A and B disjoint?', A.isdisjoint(B))
print(' A and C disjoint?', A.isdisjoint(C))
輸出:
A and B disjoint? True
A and C disjoint? False
示例 2:使用其他 iterables 作為參數使用isdisjoint()
A = {1, 2, 3, 4}
B = [5, 3, 6]
C = '3mn7'
D ={1 : 'a', 2 : 'b'}
E ={'a' : 1, 'b' : 2}
print('A and B disjoint?', A.isdisjoint(B))
print('A and C disjoint?', A.isdisjoint(C))
print('A and D disjoint?', A.isdisjoint(D))
print('A and E disjoint?', A.isdisjoint(E))
輸出:
A and B disjoint? False
A and C disjoint? False
A and D disjoint? False
A and E disjoint? True