2016-10-19 7 views
0

は、私がこのように作成10x10ノードで作られた通常のグリッドネットワークを持っていると言う:NetworkX:エッジの長さの辞書を正しく作成する方法は?

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() 

は、今私は、各エッジのために、その長さを格納した辞書を作成したいと言います。これは意図した結果である:

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

そして、これは私がその時点までに取得しようとする方法である:

from math import sqrt 

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

しかし、私は、次のエラーメッセージが表示されますよう明らかに間違って何かがある:

--------------------------------------------------------------------------- 
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 

私には何が欠けていますか?

答えて

1

G.edges()はイテレータであり有効な辞書キーではなく、G.edges()は実際には辺を生成するだけでなく、ノードの位置ではない。

これはあなたの代わりに何をしたいです:

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) 
関連する問題