确定集合是否包含不同集合中的值

时间:2016-05-16 16:57:34

标签: python python-3.x set

我希望找到一个集合是否包含除另一个集合中包含的值以外的任何值。

目前我有代码:

 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集中的字词。 [即我不想看两组之间是否存在差异,而只是输入组中是否存在不在另一组中的值]。

3 个答案:

答案 0 :(得分:5)

你可以substract这两套:

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

set_2中的每个元素都将从set_1中删除。如果结果集不为空,则表示set_1中至少有一个值未包含在set_2中。

请注意,空集会被解释为False,这就是if条件有效的原因。

答案 1 :(得分: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 :(得分:2)

set_diff = set_1.difference(set_2)
if set_diff:
    print ("additional terms")
else:
    print ("no additional terms")
相关问题