Python 中的 isdisjoint() 函式


在本文中,我們學習如何針對 set() 資料型別實現 isdisjoint() 函式。此函式檢查作為引數傳入的集合中是否有任何常見元素。如果找到任何元素,則返回 False,否則返回 True。

除了 set 輸入,isdisjoint() 函式還可以將列表、元組和字典作為輸入引數。Python 直譯器會將這些型別隱式轉換為 set 型別。

語法

<set 1>.isdisjoint(<set 2>)

返回值

布林值 True/False

下面讓我們考慮一個與實現相關的說明

示例

#declaration of the sample sets
set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = {'p','o','i','n','t'}
set_3 = {'p','y'}

#checking of disjoint of two sets
print("set1 and set2 are disjoint?", set_1.isdisjoint(set_2))
print("set2 and set3 are disjoint?", set_2.isdisjoint(set_3))
print("set1 and set3 are disjoint?", set_1.isdisjoint(set_3))

輸出

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

解釋

由於 set_1 和 set_2 有一些元素相同,因此顯示布林值 False。這與 set_2 和 set_3 之間的比較相同。但在 set_1 和 set_3 之間的比較中,顯示布林值 True,因為找不到任何相同元素。

接下來讓我們看另一個示例,其中涉及除 set 型別之外的可迭代型別。

注意:外部宣告的 set_1 必須是 set 型別,以使直譯器瞭解集合之間的比較。內部傳入的引數可以是任何型別,這些型別將隱式轉換為 set 型別。

示例

#declaration of the sample iterables
set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = ('p','o','i','n','t')
set_3 = {'p':'y'}
set_4 = ['t','u','t','o','r','i','a','l']

#checking of disjoint of two sets
print("set1 and set2 are disjoint?", set_1.isdisjoint(set_2))
print("set2 and set3 are disjoint?", set_1.isdisjoint(set_3))
print("set1 and set3 are disjoint?", set_1.isdisjoint(set_4))

輸出

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

此處還會檢查以查詢共同元素,並生成所需的輸出。

結論

在本文中,我們學習瞭如何在 Python 中使用 disjoint() 函式,以及該函式允許比較哪些型別的引數。

更新於: 2020 年 7 月 3 日

183 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.