【问题标题】:Python: Comparing value overlap between keys in a dictionaryPython:比较字典中键之间的值重叠
【发布时间】:2019-06-17 22:40:14
【问题描述】:

我有一个这样的dict

dict = defaultdict(list, {'a': [['1', '2', 'A', 'cat'],
                               ['1', '3', 'A', 'dog']], 
                          'b': [['1', '2', 'A', 'cat'],
                               ['1', '3', 'A', 'dog']],
                          'c': [['1', '2', 'A', 'cat'],
                               ['2', '2', 'A', 'snake'],
                               ['2', '2', 'A', 'bird']]}

我想使用每个值的完整列表来获取重叠值的所有成对比较。 (值列表中的每个位置都必须匹配才能被视为键之间的匹配)

由于ab 共享['1', '3', 'A', 'dog']c 没有,a/b: ['1', '3', 'A', 'dog']

abc,全部分享['1', '2', 'A', 'cat']a/b/c: ['1', '2', 'A', 'cat']

只有c['2', '2', 'A', 'snake'],所以c: ['2', '2', 'A', 'snake']

首选输出是结合上述内容的字典,例如

combine_dict = {'a/b': ['1', '3', 'A', 'dog'], 'a/b/c': ['1', '2', 'A', 'cat'], 'c': [['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}

【问题讨论】:

    标签: python list dictionary key


    【解决方案1】:

    你可以使用collections.defaultdict:

    import collections
    d = {'a': [['1', '2', 'A', 'cat'], ['1', '3', 'A', 'dog']], 'b': [['1', '2', 'A', 'cat'], ['1', '3', 'A', 'dog']], 'c': [['1', '2', 'A', 'cat'], ['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}
    new_d = collections.defaultdict(list)
    for a, b in d.items():
      for i in b:
         new_d[tuple(i)].append(a)
    
    
    new_r = collections.defaultdict(list)
    for a, b in new_d.items():
       new_r['/'.join(b)].append(list(a))
    
    new_result = {a:b[0] if len(b) == 1 else b for a, b in new_r.items()}
    

    输出:

    {'a/b/c': ['1', '2', 'A', 'cat'], 'a/b': ['1', '3', 'A', 'dog'], 'c': [['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}
    

    【讨论】:

    • 你能解释一下new_result = {'/'.join(b):list(a) for a, b in new_d.items()}吗?我尝试将其写为 for a, b in combination_dict.items(): combination_list = '/'.join(b):list(a) 以了解发生了什么,但该代码的语法无效。
    • @Liquidity {'/'.join(b):list(a) for a, b in new_d.items()} 是一个dictionary comprehension。请查看我最近的编辑,因为我以更易读的方式添加了创建 new_result 的代码
    • 感谢您的澄清!我想我发现了一个问题——如果有两个以上的值,这只保存最后一个。我更新了我的示例,使c 应该输出'c': ['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird'],但使用您的代码仅输出'c': ['2', '2', 'A', 'bird']。您很好地回答了原始示例,我应该更清楚的是,即使共享或未共享多个值,我也希望保存所有值!我应该把它作为一个新问题打开吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多