【问题标题】:Determine whether a set contains a value other than that in a different set确定一个集合是否包含不同于不同集合中的值
【发布时间】:2016-05-17 01:05:44
【问题描述】:

我正在寻找一个集合是否包含其他集合以外的任何值。

目前我有代码:

 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")

有没有更简单的方法来做到这一点?显然很容易看出一个集合是否包含一个元素 [例如union of sets],但看不到一个明显的方法来查看一个集合是否包含一个集合中的元素以外的元素。

更新

澄清一下,我只是想看看entered set 中是否有一个术语没有出现在allowable 集中。 [即不查看两组之间是否存在差异,而只是查看输入的一组中是否存在另一组中没有的值]。

【问题讨论】:

  • 这就是set.difference() 的用途
  • 更新后:这仍然是set.difference 的用途:{1,2}.difference({2,3}) -> {1} 它不担心包含在第二组中而不是第一组中的内容。
  • 你可能会想到set.symmetric_difference{1,2}.symmetric_difference({2,3}) -> {1,3}

标签: python python-3.x set


【解决方案1】:

你可以substract两套:

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

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

请注意,空集被解释为False,这就是if 条件起作用的原因。

【讨论】:

    【解决方案2】:

    简单计算两个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
    

    【讨论】:

      【解决方案3】:
      set_diff = set_1.difference(set_2)
      if set_diff:
          print ("additional terms")
      else:
          print ("no additional terms")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多