如果它们之间有共同的字符串,是否有一种逻辑合并多个字典的方法?即使这些常见字符串在一个dict()的值与另一个的键之间匹配?
我在SO上看到很多类似的问题,但似乎没有解决我将"低级文件"中的多个键与高键/值中的多个键相关联的具体问题(level1dict)
说我们有:
level1dict = { '1':[1,3], '2':2 }
level2dict = { '1':4, '3':[5,9], '2':10 }
level3dict = { '1':[6,8,11], '4':12, '2':13, '3':[14,15], '5':16, '9':17, '10':[18,19,20]}
finaldict = level1dict
Run Code Online (Sandbox Code Playgroud)
当我在逻辑上说我的意思是,在level1dict 1 = 1,3并且在level2dict 1 = 4和3 = 5,9所以整体(到目前为止)1 = 1,3,4,5,9(排序并不重要)
我想得到的结果是
#.update or .append or .default?
finaldict = {'1':[1,3,4,5,9,6,8,11,12,14,15,16,17] '2':[2,10,18,19,20]}
Run Code Online (Sandbox Code Playgroud)
回答:谢谢Ashwini Chaudhary和Abhijit的networkx模块.
这是连接组件子图的问题,如果要使用networkx,可以最好地确定.这是您的问题的解决方案
>>> import networkx as nx
>>> level1dict = { '1':[1,3], '2':2 }
>>> level2dict = { '1':4, '3':[5,9], '2':10 }
>>> level3dict = { '1':[6,8,11], '4':12, '2':13, '3':[14,15], '5':16, '9':17, '10':[18,19,20]}
>>> G=nx.Graph()
>>> for lvl in level:
for key, value in lvl.items():
key = int(key)
try:
for node in value:
G.add_edge(key, node)
except TypeError:
G.add_edge(key, value)
>>> for sg in nx.connected_component_subgraphs(G):
print sg.nodes()
[1, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17]
[2, 10, 13, 18, 19, 20]
>>>
Run Code Online (Sandbox Code Playgroud)
这是你如何想象它
>>> import matplotlib.pyplot as plt
>>> nx.draw(G)
>>> plt.show()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |