简体   繁体   中英

NetworkX: how to properly create a dictionary of edge lengths?

Say I have a regular grid network made of 10x10 nodes which I create like this:

import networkx as nx
from pylab import *
import matplotlib.pyplot as plt
%pylab inline

ncols=10 

N=10 #Nodes per side
G=nx.grid_2d_graph(N,N)
labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds=[(N-j-1,N-i-1) for i,j in inds]
posk=dict(zip(vals,inds))
nx.draw_networkx(G, pos=posk, with_labels=True, node_size = 150, node_color='blue',font_size=10)
plt.axis('off')
plt.title('Grid')
plt.show()

Now say I want to create a dictionary which stores, for each edge, its length. This is the intended outcome:

d={(0,1): 3.4, (0,2): 1.7, ...}

And this is how I try to get to that point:

from math import sqrt

lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}

But there clearly is something wrong as I get the following error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-c73c212f0d7f> in <module>()
      2 from math import sqrt
      3 
----> 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}
      5 
      6 

<ipython-input-7-c73c212f0d7f> in <dictcomp>(***failed resolving arguments***)
      2 from math import sqrt
      3 
----> 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}
      5 
      6 

TypeError: 'int' object is not iterable

What am I missing?

There is a lot going wrong in the last line, first and foremost that G.edges() is an iterator and not a valid dictionary key, and secondly, that G.edges() really just yields the edges, not the positions of the nodes.

This is what you want instead:

lengths = dict()
for source, target in G.edges():
    x1, y1 = posk[source]
    x2, y2 = posk[target]
    lengths[(source, target)] = math.sqrt((x2-x1)**2 + (y2-y1)**2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM