NetworkX:使用for循环遍历图

时间:2020-02-26 08:14:07

标签: python networkx

假设我在一个项目中有四个不同的图,并且我想使用for循环遍历它们。首先,图形结构将如下所示:

import networkx as nx
Gx = nx.DiGraph()
Gx.add_node('x1', server = 5)
Gx.add_node('x2', service = 3)
Ga = nx.DiGraph()
Ga.add_node('a1', server = 8)
Ga.add_node('a2', service = 4)
Gb = nx.DiGraph()
Gb.add_node('b1', server = 12)
Gb.add_node('b2', service = 5)
Gc = nx.DiGraph()
Gc.add_node('c1', server = 5)
Gc.add_node('c2', service = 3)

现在,在将属性设置为0(例如,模拟服务器故障)之后,我想遍历每张图并随机选择一个节点。因此,我的函数应如下所示:

for 'every graph' in 'DiGraphs':
     random_node = random.sample(Gx/a/b/c.nodes, 1)
     new_value_random_node = random_node['attribute'] * 0

然后在执行代码后将这样抛出图结构:

import networkx as nx
Gx = nx.DiGraph()
Gx.add_node('x1', server = 5)
Gx.add_node('x2', service = 0)  # service fail
Ga = nx.DiGraph()
Ga.add_node('a1', server = 0)  # server fail
Ga.add_node('a2', service = 4)
Gb = nx.DiGraph()
Gb.add_node('b1', server = 0)  # server fail
Gb.add_node('b2', service = 5)
Gc = nx.DiGraph()
Gc.add_node('c1', server = 5)
Gc.add_node('c2', service = 0)  # service fail

总结我想做两件事:
1。浏览每个图形(Gx,Ga,Gb,Gc)
2。在每张图中->随机选择一个节点
3。设置随机节点(服务器或服务)的属性= 0

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

我提出以下建议:

import networkx as nx
Gx = nx.DiGraph()
Gx.add_node('x1', server = 5)
Gx.add_node('x2', service = 3)
Ga = nx.DiGraph()
Ga.add_node('a1', server = 8)
Ga.add_node('a2', service = 4)
Gb = nx.DiGraph()
Gb.add_node('b1', server = 12)
Gb.add_node('b2', service = 5)
Gc = nx.DiGraph()
Gc.add_node('c1', server = 5)
Gc.add_node('c2', service = 3)

import random
for graph in [Gx, Ga, Gb, Gc]:
     random_node = random.sample(graph.nodes, 1)[0]
     attr = list(graph.nodes.data()[random_node].keys())[0]
     graph.nodes[random_node][attr] = 0