您可以使用add_edge 函数向MultiDiGraph 中的现有边添加新属性,但您需要注意key 关键字(其值必须为0)。
在我的示例中,我将tcv1 属性添加到第一个“a”->“b”边(我使用您的变量名和使用add_edges_from 创建的示例图):
import networkx as nx
router_matrix = nx.MultiDiGraph()
# add two weighted edges ("a" -> "b" and "b" -> "a")
router_matrix.add_edges_from([
("a", "b", {"weight": 0.5}),
("b", "a", {"weight": 0.99})
])
# print list of edges with all data
print(router_matrix.edges(data=True))
tmp_path = [["a", "b"], ["b", "a"]]
traffic_cv = [42, 66]
# add "tcv1" for only the first edge of tmp_path
router_matrix.add_edge(tmp_path[0][0], tmp_path[0][1], key=0, tcv1=traffic_cv[0])
print(router_matrix.edges(data=True))
要将tcv1 添加到所有边缘,您可以使用router_matrix.edges() 遍历所有边缘(注意这里我使用G[src_node][dest_node][key][attribute] 语法而不是add_edge):
# add new attribute to all edges
counter = 0
for src, dest in router_matrix.edges():
router_matrix[src][dest][0]['tcv1'] = traffic_cv[counter]
counter += 1
print(router_matrix.edges(data=True))