python - 合并 python 集合字典

标签 python algorithm dictionary

我有一个包含 2 种节点的图表——“字母节点”(L) 和“数字节点”(N)。我有 2 个字典,一个显示从 L 到 N 的边,另一个显示从 N 到 L 的边。

 A = {0:(b,), 1:(c,), 2:(c,), 3:(c,)}
 B = {a:(3,), b:(0,), c:(1,2,3)} 

键值对 c:(1,2,3) 表示从 c1,2,3 有边(3条边)

我想将这些合并到一个字典 C 以便结果是一个新字典:

C = {(0,): (b,), (1, 2, 3): (a, c)}

C = {(b,):(0,), (a, c):(1, 2, 3)}

在生成的字典中,我希望字母节点和数字节点位于键和值的不同侧。我不在乎哪个是键或值只需要将它们分开。我怎样才能有效地解决这个问题?

澄清:这是一个具有 2 种节点类型的图 - 数字节点和字母节点。字典 C 说从字母节点 (a,c) 可以到达数字节点 (1,2,3) 即 a->3->c->1, a->3->c->2 这样你就可以从 a 得到 1,2,3。即使没有从 a 到 2 或 a 到 1 的直边。

最佳答案

根据您的说法,我猜您正在尝试寻找图算法。

import itertools
def update_dict(A, result): #update vaules to the same set
    for k in A:
        result[k] = result.get(k, {k}).union(set(A[k]))
        tmp = None
        for i in result[k]:
            tmp = result.get(k, {k}).union(result.get(i, {i}))
        result[k] = tmp
        for i in result[k]:
            result[i] = result.get(i, {i}).union(result.get(k, {k}))

A = {0:('b',), 1:('c',), 2:('c',), 3:('c',)}
B = {'a':(3,), 'b':(0,), 'c':(1,2,3)}
result = dict()
update_dict(A, result)
update_dict(B, result)
update_dict(A, result) #update to fix bugs
update_dict(B, result)

k = sorted([sorted(list(v)) for v in result.values()]) 
k = list( k for k, _ in itertools.groupby(k))  #sort and remove dumplicated set

final_result = dict()
for v in k: #merge the result as expected
    final_result.update({tuple([i for i in v if isinstance(i, int)]):tuple([i for i in v if not isinstance(i, int)])})
print final_result

#output
{(0,): ('b',), (1, 2, 3): ('a', 'c')}

关于python - 合并 python 集合字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32264099/

相关文章:

python - 从下拉列表中选择选项后如何抓取数据框?

python - 查找图像的边缘

python - 动态传递字典名称python

python - 一次替换字符串中的所有字符

json - 如何访问嵌套在 Oxford Dictionaries API 的多层数组和字典中的定义键?

python - 正则表达式匹配地址与子模式

python - Django - JSON 序列化错误

algorithm - 计算算法时间复杂度的资源

python - 处理 IPython 集群中的各种资源需求

java - 如何在此代码中显示负数阶乘