2015-10-26 58 views
2

我對Python和NetworkX都是新手。我有一個正方形,正常圖GNxN節點(一個晶格)。這些節點通過dict(參見下面的代碼)進行標記。現在我想讓edgelist返回每個邊的開始端點,而不是通過參考節點座標,而是返回給定節點的標籤。用'labels`字典替換`edgelist`的值

例子:

N = 3 
G=nx.grid_2d_graph(N,N) 
labels = dict(((i, j), i + (N-1-j) * N) for i, j in G.nodes()) 
#This gives nodes an attribute ID that is identical to their labels 
for (i,j) in labels: 
    G.node[(i,j)] ['ID']= labels[(i,j)] 
edgelist=G.edges() #This gives the list of all edges in the format (Start XY, End XY) 

如果我N=3運行它,我得到:

In [14]: labels 
Out[14]: {(0, 0): 6, (0, 1): 3, (0, 2): 0, (1, 0): 7, (1, 1): 4, (1, 2): 1, (2, 0): 8, (2, 1): 5, (2, 2): 2} 

該方案標籤左上角節點0,與節點(N-1)th被放置在右下角。這就是我想要的。現在,隨着edgelist問題:

In [15]: edgelist 
Out [15]: [((0, 1), (0, 0)), ((0, 1), (1, 1)), ((0, 1), (0, 2)), ((1, 2), (1, 1)), ((1, 2), (0, 2)), ((1, 2), (2, 2)), ((0, 0), (1, 0)), ((2, 1), (2, 0)), ((2, 1), (1, 1)), ((2, 1), (2, 2)), ((1, 1), (1, 0)), ((2, 0), (1, 0))] 

我試圖解決這些線路的問題(靈感來自這裏:Replace items in a list using a dictionary):

allKeys = {} 
for subdict in (labels): 
    allKeys.update(subdict) 

new_edgelist = [allKeys[edge] for edge in edgelist] 

,但我得到這個啓迪我週一美妙的事情:

TypeError: cannot convert dictionary update sequence element #0 to a sequence 

總結,我希望能夠替換的元素列表與labels字典的值相比較,以便從((2,0),(1,0))(其對應於節點和)的邊緣返回(8,7)不盡的感謝!

回答

1

我相信你正在尋找的是簡單nx.relabel_nodes(G,labels,False)這裏是documentation

Here is the output when I printed the nodes of G before and after calling the relabel nodes function.

# Before relabel_nodes 
[(0, 1), (1, 0), (0, 0), (1, 1)] 
# After relabel_nodes 
[0, 1, 2, 3] 

After doing this, the edge labels automatically becomes what you expect.

# Edges before relabelling nodes 
[((0, 1), (0, 0)), ((0, 1), (1, 1)), ((1, 0), (0, 0)), ((1, 0), (1, 1))] 
# Edges after relabelling nodes 
[(0, 1), (0, 2), (1, 3), (2, 3)] 

而且,我已經在你創建,但聊天回答這個問題似乎你沒有通知。

+1

非常感謝。我確實在聊天中遇到了很多問題,所以我沒有通知。我很抱歉沒有閱讀過此信息。 :) – FaCoffee

+0

順便說一句,該文檔不是很有幫助和描述。如果'G'是我的圖形,'labels'是另一個問題中設置的那些,我怎麼能確定沒有引入跳轉/缺陷/錯誤?我想這是因爲'標籤'的定義方式正確嗎? – FaCoffee

+1

我不太清楚我是否理解你的問題。但是,標籤定義對完美無缺的結果至關重要 –