Reputation: 1109
I have two line graphs of equal length and parallel to each other in networkx, how can i loop over the graphs and connect opposite nodes with two edges ie connect 2 & 2a, 3 & 3a etc
nodes1 = [2,5,7,8,9,10]
nodes2 = ['2a','5a','7a','8a','9a','10a']
I tried
for k in range (0, len(nodes1)):
for i in range (0, len(nodes2)):
if nodes1.index(kk) == nodes2.index(i):
X.add_edge(k,i)
But it dosent give the desired output please can anyone correct me. Thanks
This is what I have
2---------3---------4----------5----------6
2a---------3a-------4a--------5a---------6a
This is what I want
2---------3---------4----------5-----------6
|| || || || ||
|| || || || ||
|| || || || ||
2a--------3a---------4a---------5a---------6a
Sorry if the previous post was not clear
Upvotes: 1
Views: 97
Reputation: 393883
The reason your code does not work as is, is because index returns the index in the list where the value resides, so you are looping from 0
to the length of each list and the first value 0
does not exist in your list which throws a ValueError
. See the online docs: http://docs.python.org/2/tutorial/datastructures.html
If you just wanted to create the tuple pairs and assuming lengths and ordering were already correct then if you modify your code with this line:
for k in range (0, len(nodes1)):
X.add_edge(nodes1[k],nodes2[k])
would achieve what you want as you want to traverse both lists in parallel, your original code even if index
didn't raise a ValueError
would have resulted in 5 x 5
entries as you were adding an edge for every entry in nodes2
for each node in node1
which is not what you wanted.
Assuming your ordering matches for both lists then you can do a list comprehension to create the edge list and create your graph from this
In [171]:
edge_list = [(nodes1[i], nodes2[i]) for i in range(len(nodes1))]
# I'm using python 3 so you could do the following also
# edge_list = list(zip(nodes1, nodes2))
G=nx.DiGraph()
G.add_edges_from(edge_list)
G.edges()
Out[171]:
[(2, '2a'), (5, '5a'), (7, '7a'), (8, '8a'), (9, '9a'), (10, '10a')]
EDIT
If you want to add edges in both directions then you just create a secondary edge_list like so by swapping the order of the lists around:
In [194]:
edge_list_reversed = list(zip(nodes2, nodes1))
edge_list_reversed
G.add_edges_from(edge_list_reversed)
G.edges()
Out[194]:
[(2, '2a'),
(5, '5a'),
(7, '7a'),
(8, '8a'),
(9, '9a'),
(10, '10a'),
('2a', 2),
('8a', 8),
('9a', 9),
('5a', 5),
('10a', 10),
('7a', 7)]
Upvotes: 2