【问题标题】:How to define multiple attributes for an edge in multi Digraph如何在多有向图中为一条边定义多个属性
【发布时间】:2016-11-21 19:28:25
【问题描述】:

我有一个有四个节点的图,每个节点之间有两条有向边(a 到 b 和 b 到 a),所以我使用了一个多重有向图。该图已经具有默认定义的“权重”属性,在我的情况下,该属性代表交通流的每个边的容量。我需要为每条边定义另外两个属性,比如说 tcv1 和 tcv2。

作为 Python 和 networkx 的初学者,我无法弄清楚这一点。一些谷歌搜索带我here,但我无法正确使用它。

add_attribute_to_edge(router_matrix, tmp_path[0][0], tmp_path[0][1], 'tcv1', traffic_cv[0])

我使用上面的代码,其中 router_matrix 是图形,tmp_path[x][x] 将表示节点名称,如“a”或“b”,tcv1 是属性,代码中的 traffic_cv[0] 将是计算的整数。打印 tcv1 只会给出 {}。

有人可以提出解决方案或指出我哪里出错了。

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    您可以使用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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-07
      • 2010-10-01
      • 1970-01-01
      • 2021-05-27
      • 2021-09-08
      • 2016-02-23
      • 2016-01-17
      相关资源
      最近更新 更多