2016-05-16 171 views
0

我正在查找集合是否包含除包含在另一集合中的集合之外的任何值。確定一個集合是否包含不同於另一集合中的值的集合

目前我的代碼:

set_entered = set(["ok_word_1", "ok_word_2", "not_ok_word"]) 
set_allowable = set(["ok_word_1", "ok_word_2","ok_word_3", "ok_word_4"]) 

set_entered_temp = set(set_entered) 
for item in set_allowable : 
    set_1_temp.discard(item) 
if len(set_entered_temp) > 0: 
    print ("additional terms") 
else: 
    print ("no additional terms") 

是否有這樣做的一個簡單的方法?顯然很容易看到一個集合是否包含一個元素[例如集合],但看不到一個明顯的方式來看一個集合是否包含一個元素而不是集合中的元素。

更新

只是爲了澄清,我只是想看看是否有在entered set這個術語沒有出現在allowable集。 [也就是說,並不是要看看兩組之間是否存在差異,而是要看輸入組中是否有值不在另一組中]。

+1

那就是'set.difference()'是 – Kasramvd

+1

您更新後:這仍然是什麼'set.difference'是:'{1,2} .difference({2 ,3}) - > {1}「它不擔心第二組中包含的內容,但不包含第一組中的內容。 –

+0

您可能會考慮['set.symmetric_difference'](https://docs.python.org/2/library/stdtypes.html#set.symmetric_difference):'{1,2} .symmetric_difference({2,3 }) - > {1,3}' –

回答

5

可以substract兩套:

if set_1 - set_2: 
    print("Additional terms") 

set_2每個元素都將set_1被刪除。如果結果集不爲空,這意味着set_1中至少有一個值不包含在set_2中。

請注意,空集被解釋爲False,這就是爲什麼if條件起作用。

3

只需計算兩個sets的差異即可。

difference(other, ...)

set - other - ...

返回一個新的集合與集合 元素不在別人。

x = bool(set_1 - set_2) # if boolean is needed 

if set_1 - set_2: # simple check in boolean context 
    pass 
2
set_diff = set_1.difference(set_2) 
if set_diff: 
    print ("additional terms") 
else: 
    print ("no additional terms") 
相關問題