我太困惑了,无法提出正确的方法:
并有两个字典,分别显示出场和入场分数
graph_to = {'a':{'b':2,'c':3},'b':{'a':1,'d':4}}
graph_from = {'a':{'b':1},'b':{'a':2},'c':{'a':3},'d':{'b':4}}
例如,在graph_to
中,节点a
进入得分为2的节点b
,然后进入得分为3的节点c
。并在graph_from
节点a
中收到节点b
的得分1。
我想创建undirected graph
以便对两个节点之间的分数求和。它应该成为这本字典:
graph = {
'a':{'b':3,'c':3},
'b':{'a':3,'d':4},
'c':{'a':3},
'd':{'b':4}
}
答案 0 :(得分:2)
您可以尝试制作collections.defaultdict()
个对象collections.Counter()
,并在迭代两个图格时求和边计数:
Process current = Process.GetCurrentProcess();
// Enumerate through all the process resources on the share
// local computer that the specified process name.
foreach (Process process in
Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
NativeMethods.SetForegroundWindow( process.MainWindowHandle);
NativeMethods.ShowWindow(process.MainWindowHandle,
WindowShowStyle.Restore);
break;
}
}
哪个给:
from collections import defaultdict
from collections import Counter
from pprint import pprint
graph_to = {'a':{'b':2,'c':3},'b':{'a':1,'d':4}}
graph_from = {'a':{'b':1},'b':{'a':2},'c':{'a':3},'d':{'b':4}}
undirected_graph = defaultdict(Counter)
def sum_edges(graph, result):
for node, edges in graph.items():
for edge in edges:
result[node][edge] += edges[edge]
sum_edges(graph_to, undirected_graph)
sum_edges(graph_from, undirected_graph)
pprint(undirected_graph)
注意:defaultdict(<class 'collections.Counter'>,
{'a': Counter({'b': 3, 'c': 3}),
'b': Counter({'d': 4, 'a': 3}),
'c': Counter({'a': 3}),
'd': Counter({'b': 4})})
和Counter
是defaultdict
的子类,因此您可以将它们与普通词典一样对待。
如果您确实想要最终无向图中的普通字典,则可以使用以下两种dict理解之一:
dict
此外,您还可以在此处使用dict.update()
重构dict((k, dict(v)) for k, v in undirected_graph.items())
# {'a': {'b': 3, 'c': 3}, 'b': {'a': 3, 'd': 4}, 'c': {'a': 3}, 'd': {'b': 4}}
{k: dict(v) for k, v in undirected_graph.items()}
# {'a': {'b': 3, 'c': 3}, 'b': {'a': 3, 'd': 4}, 'c': {'a': 3}, 'd': {'b': 4}}
:
sum_edges()
答案 1 :(得分:0)
我希望我们很乐意掌握一切,这里有简单的逻辑
out_dict = {}
for key in graph_to :
for sub_key in graph_to[key]:
if key in graph_from and sub_key in graph_from[key]:
out_dict[key] = {sub_key: graph_to[key][sub_key] + graph_from[key][sub_key]}
else:
out_dict[key].update({sub_key: graph_to[key][sub_key]})
graph_from.update(out_dict)
print(graph_from)
输出:
{'a': {'b': 3, 'c': 3}, 'b': {'a': 3, 'd': 4}, 'c': {'a': 3}, 'd': {'b': 4}}