我有一个包含 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)
表示从 c
到 1,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/