我有一本很大的字典,里面有一个目录。我想以一种有效的方式对列表中至少有一个元素的所有键进行分组。例如:
dictionary = {'group1': ['a', 'b', 'c', 'd'],
'group2': ['a', 'b', 'c', 'd', 'e'],
'group3': ['f', 'g', 'h'],
'group4': ['g', 'z']}
group_dict(dictionary)
会回馈:
^{pr2}$更新
字典的“真实”结构是:
dictionary = {'group1' :{'IDs': ['a','b','c','d'], 'oldest_node': 'node_30'}, 'group2' :{'IDs': ['c','d','e'], 'oldest_node': 'node_40'}, 'group3' :{'IDs': ['h','k'], 'oldest_node': 'node_2'}, 'group4' :{'IDs': ['z','w','x','j'], 'oldest_node': 'node_6'}, 'group3' :{'IDs': ['h','z'], 'oldest_node': 'node_9'}
我希望生成包含性最强的组并保持节点变量的最小值:
dictionary = {'group1' :{'IDs': ['a','b','c','d','e'], 'oldest_node': 'node_30'}, 'group3' :{'IDs': ['h','k','z','w','x','j'], 'oldest_node': 'node_2'}}
下面的程序解决了原来的问题。也许有一种更有效的算法,但我认为这个算法相当快。在
修改此代码以处理更新版本中更复杂的dict应该不太困难。在
(我使用的是Python2.6,所以没有dict理解,这就是为什么我使用生成器表达式构建dict)。在
合并_列表.py
输出
^{pr2}$这是一个在更新的dict结构上工作的版本。在
输出
是否确实要更改用作输入的词典,或者如果函数因此输出另一个词典,是否可以?在
下面是一个快速而脏的函数,它将值分组:
它应该返回:
^{pr2}$展开函数以删除重复项。在
我使用的是内置的}。这应该是您的核心需求的关键。
在double for循环(非常难看)中,比较字典中的值,如果找到交集,则将值的并集转换为list并分配给结果字典。这真的不是一个好的解决方案,但也许它能给你一些想法。在
set
及其方法intersection
和{相关问题 更多 >
编程相关推荐