【问题标题】:Remove a given element from the other set in a dict of two sets从两个集合的字典中的另一个集合中删除给定元素
【发布时间】:2010-07-30 03:55:14
【问题描述】:

我有一个字典,{ "foo": set(["a", "b"]), "bar": set(["c", "d"]) },我得到了两个集合之一的一个元素和 other 集合的名称。我需要删除该元素。我该怎么做呢?到目前为止,我最好的尝试是:

keys = dict.keys()
if Element in dict[keys[0]].union(dict[keys[1]]):
  dict[keys[abs(keys.index(Other_Set) - 1)]].remove(Element)

不过,这似乎有点过分了;有什么办法可以改进吗?

【问题讨论】:

    标签: python dictionary set


    【解决方案1】:

    试试这个:

    dictionary['foo' if otherset == 'bar' else 'bar'].discard(element)
    

    【讨论】:

    • 我最喜欢这个。正如马修指出的那样,我只是将删除替换为丢弃。
    • @Plumenator,是的,意识到之后会更好。 :-)
    • 由于键('foo' 和 'bar')是用户输入的,所以一旦实现就不会那么漂亮了,但我还是喜欢它。谢谢您的帮助。 :)
    【解决方案2】:

    使用字典查找另一组:

    >>> other={'foo':'bar','bar':'foo'}
    >>> d = { "foo": set(["a", "b"]), "bar": set(["b", "c"]) }
    >>> element = "b"
    >>> setname = "bar"
    >>> d[other[setname]].discard(element)
    >>> d
    {'foo': set(['a']), 'bar': set(['c', 'b'])}
    

    【讨论】:

      【解决方案3】:

      怎么样:

      keys = dict.keys()
      dict[keys[1 - keys.index(Other_Set)]].discard(Element)
      

      使用discard,如果元素不在集合中,您不会得到KeyError。因此,您不需要检查(另一种选择是忽略KeyError)。而1 - 消除了对abs 的需求。

      【讨论】:

        【解决方案4】:

        如果您事先不知道dct 中的键名,这个可能适合您:

        dct={ "foo": set(["a", "b"]), "bar": set(["c", "d"]) }
        
        element='b'
        other_set='bar'
        
        for key,value in dct.iteritems():
            if key != other_set:
                value.discard(element)
        
        print(dct)
        # {'foo': set(['a']), 'bar': set(['c', 'd'])}
        

        【讨论】:

          【解决方案5】:
          element = "b"
          other = "bar"
          d = { "foo": set(["a", "b"]), "bar": set(["b", "c"]) }
          theSet = d[[s for s in d.iterkeys() if s != other][0]]
          theSet.discard(element)
          

          【讨论】:

            【解决方案6】:

            我的变体,对于任意数量的集合都是通用的,为所有其他人取出给定的项目:

            dict_of_sets={'foo':set(['a','b','c']),'bar': set(['d','b','e']),'onemore': set(['a','e','b'])}
            givenset,givenitem='bar','b'
            otherset= (key for key in dict_of_sets if key != givenset)
            for setname in otherset:
              dict_of_sets[setname].discard(givenitem)
            
            print dict_of_sets
            
            """Output:
            {'foo': set(['c', 'a']), 'bar': set(['e', 'b', 'd']), 'onemore': set(['e', 'a'])}
            """
            

            【讨论】:

              【解决方案7】:

              这是一种更“pythonic”的方式:

              >>> d = { "foo": set(["a", "b"]), "bar": set(["b", "c"]) }
              
              >>> d['foo']-=d['bar']
              >>> d
              {'foo': set(['a']), 'bar': set(['c', 'b'])}
              

              当然,d['foo'] 可以是 d[hashable_key],其中 hashable_key 具有用户输入或你有什么。

              Recall that the operators - & ^ | on sets 被重载到各自的变异方法:

              a_set.difference_update(other_set) # also "-"
              a_set.intersection_update(other_set) # also "&"
              a_set.symmetric_difference_update(other_set) # also "^"
              a_set.update(other_set) # also "-"
              

              然后您可以使用扩充赋值 -= 来修改 'foo' 的设置值。这里提供的所有其他解决方案对我来说似乎太罗嗦了。

              编辑我误读了 OP,并忽略了这个作为答案。我投票赞成the best solution

              【讨论】:

              • @Plumenator:我误读了 OP,并专注于结果是集合之间的差异。对不起...
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-08
              • 1970-01-01
              • 2011-05-23
              • 2017-04-11
              相关资源
              最近更新 更多