代码之家  ›  专栏  ›  技术社区  ›  Prabhu

求两个复杂词典的集合差

  •  2
  • Prabhu  · 技术社区  · 15 年前

    我有两本字典的结构如下:

    a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]}
    b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]}
    

    我需要找出字典中每个键之间的设置差异,即dict1['a']-dict2['a']应该返回[3,4]。任何想法都会受到赞赏。

    4 回复  |  直到 12 年前
        1
  •  2
  •   S.Lott    15 年前

    对于您要做的事情,您的数据结构是错误的。

    用这个代替。

    dict1 = {'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]}
    dict2 = {'a': [(1, 2), (5, 6)], 'b': [(1, 2), (7, 8)]}
    

    当您尝试对元组之类的不可变对象执行set操作时,生活会更简单。

    这将把列表列表转换为元组列表。

    >>> dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 )
    {'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]}
    

    这是完整的解决方案。

    >>> dict1t= dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 )
    >>> dict2t= dict( (key,[tuple(v) for v in dict2[key]]) for key in dict2 )
    >>> set(dict1t['a'])-set(dict2t['a'])
    set([(3, 4)])
    
        2
  •  6
  •   Alex Martelli    15 年前

    使用可变项(如列表)会使问题更加困难,因为它排除了简单使用Python set 数据结构。可能值得制作临时副本/版本,这些副本/版本实际使用元组代替那些烦人的列表:

    def tempaux(d):
      return dict((k, set(tuple(x) for x in v))
                  for k, v in d.iteritems())
    

    现在:

    def thedifs(dd1, dd2)
      d1 = tempaux(dd1)
      d2 = tempaux(dd2)
      allkeys = set(d1).update(d2)
      empty = set()
      difs = []
      for k in allkeys:
        s1 = d1.get(k, empty)
        s2 = d2.get(k, empty)
        adif = s1 - s2
        if adif: difs.append(adif)
      return difs
    

    这假定实际的设置差异而不是对称差异等。当然,您可以在返回&c之前将元组返回到列表中,具体取决于您的具体要求。

        3
  •  3
  •   Kenan Banks    15 年前
    >>> s1 = set([(1,2), (3,4)])
    >>> s2 = set([(1,2), (5,6)])
    >>> s1 - s2
    {(3, 4)}
    
        4
  •  2
  •   Fan    12 年前

    适用于A、B结构相同时的列表、口述或数字。

    c={'a':'1','b':'2'}
    d={'a':'10','b':'20'}
    e={'x':c,'t':15}
    f={'x':d,'t':19}
    
    def diff(a,b):
        if isinstance(a, int) and isinstance(b, int):
            b = b - a
            return b
        if isinstance(a, str) and isinstance(b, str):
            if a.isdigit() and b.isdigit():
                b = str(int(b) - int(a))
                return b
            else:
                b = a
                return b
        if type(a) is list and type(b) is list:
            for i in range(len(a)):
                b[i] = diff(a[i],b[i])
            return b
        if type(a) is dict and type(b) is dict:
            for k,v in b.iteritems():
                b[k] = diff(a[k],b[k])
            return b
    
    print diff(e,f)