Python:比较字典中键之间的值重叠

2024-04-25 17:35:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个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']]}

Tags: 内容列表字典dictlistcatdogsnake
1条回答
网友
1楼 · 发布于 2024-04-25 17:35:10

您可以使用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']]}

相关问题 更多 >

    热门问题