I have MULTIPLE line graphs of equal length and parallel to each other in networkx MultiDigraph, how can I loop over the graphs and add edges to opposite nodes with edges (N.B. the nodes are in a nested list) s ie connect 2 & 2a, 3 & 3a etc

nodes1 = [[2,5,7,8,9,10],[3,15,37,58,69,10]]
nodes2 = [['2a','5a','7a','8a','9a','10a'],['3a','15a','37a','58a','69a','10a']] 
                              BEFORE
            2---------3---------4----------5----------6



           2a---------3a-------4a--------5a---------6a


                               AFTER
            2---------3---------4----------5----------6
           | |       | |       | |        | |        | |
           | |       | |       | |        | |        | |
           | |       | |       | |        | |        | |
           2a--------3a--------4a----------5a--------6a
有帮助吗?

解决方案

Assuming the lengths of the list match and the sublists match then you can do this:

In [33]:

import networkx as nx
nodes1 = [[2,5,7,8,9,10],[3,15,37,58,69,10]]
nodes2 = [['2a','5a','7a','8a','9a','10a'],['3a','15a','37a','58a','69a','10a']] 

In [47]:
# build an edge list    
edge_list = []
# iterate over the length of the lists, access each list and zip them
for i in range(len(nodes1)):
    edge_list = edge_list + (list(tuple(zip(nodes1[i], nodes2[i]))))
    # now add the opposite direction
    edge_list = edge_list + (list(tuple(zip(nodes2[i], nodes1[i]))))
edge_list
0
1
Out[47]:
[(2, '2a'),
 (5, '5a'),
 (7, '7a'),
 (8, '8a'),
 (9, '9a'),
 (10, '10a'),
 ('2a', 2),
 ('5a', 5),
 ('7a', 7),
 ('8a', 8),
 ('9a', 9),
 ('10a', 10),
 (3, '3a'),
 (15, '15a'),
 (37, '37a'),
 (58, '58a'),
 (69, '69a'),
 (10, '10a'),
 ('3a', 3),
 ('15a', 15),
 ('37a', 37),
 ('58a', 58),
 ('69a', 69),
 ('10a', 10)]
In [48]:

G = nx.DiGraph()
G.add_edges_from(edge_list)
G.edges()
Out[48]:
[(2, '2a'),
 (3, '3a'),
 (5, '5a'),
 (7, '7a'),
 (8, '8a'),
 (9, '9a'),
 (10, '10a'),
 (15, '15a'),
 ('5a', 5),
 ('69a', 69),
 ('2a', 2),
 (69, '69a'),
 ('7a', 7),
 (37, '37a'),
 ('8a', 8),
 ('9a', 9),
 ('10a', 10),
 ('15a', 15),
 ('58a', 58),
 ('37a', 37),
 (58, '58a'),
 ('3a', 3)]

In [49]:

nx.draw(G)

enter image description here

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top