2010-11-18 44 views
3

我有我自己的對象,比如辣香腸。我有一份來自每個意大利辣香腸和一份胡椒粉的清單。然後我使用networkx構建一個圖。我試圖找到從一個意式香腸到另一個意式香腸的最短路徑的重量。然而,我發現了一個錯誤,如下所示,它跟蹤從networkx內在的東西如下:使用networkx與我自己的對象

Traceback (most recent call last): 


File "<stdin>", line 1, in <module> 
    File "pizza.py", line 437, in shortestPath 
    cost = nx.shortest_path_length(a, spepp, tpepp, True) 
    File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/generic.py", line 181, in shortest_path_length 
    paths=nx.dijkstra_path_length(G,source,target) 
    File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/weighted.py", line 119, in dijkstra_path_length 
    (length,path)=single_source_dijkstra(G,source, weight = weight) 
    File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/weighted.py", line 424, in single_source_dijkstra 
    edata=iter(G[v].items()) 
    File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/classes/graph.py", line 323, in __getitem__ 
    return self.adj[n] 
KeyError: <pizza.pepperoni object at 0x100ea2810> 

任何想法,什麼是錯誤,或者我要爲了添加到我的比薩類不算什麼得到這個KeyError?

編輯:我有我的邊格式正確。我不知道對象是否可以作爲節點處理。

回答

3

如果您將邊緣和節點分別作爲列表,則在網絡x中構建圖形很簡單。鑑於在構建圖形對象時發生的問題,也許是最好的診斷是一步要經過圖形建設networkx步:

import networkx as NX 
import string 
import random 

G = NX.Graph() # initialize the graph 

# just generate some synthetic data for the nodes and edges: 
my_nodes = [ ch for ch in string.ascii_uppercase ] 
my_nodes2 = list(my_nodes) 
random.shuffle(my_nodes2) 
my_edges = [ t for t in zip(my_nodes, my_nodes2) if not t[0]==t[1] ] 

# now add the edges and nodes to the networkx graph object: 
G.add_nodes_from(my_nodes) 
G.add_edges_from(my_edges) 

# look at the graph's properties: 
In [87]: len(G.nodes()) 
Out[87]: 26 

In [88]: len(G.edges()) 
Out[88]: 25 

In [89]: G.edges()[:5] 
Out[89]: [('A', 'O'), ('A', 'W'), ('C', 'U'), ('C', 'F'), ('B', 'L')] 

# likewise, shortest path calculation is straightforward 
In [86]: NX.shortest_path(G, source='A', target='D', weighted=False) 
Out[86]: ['A', 'W', 'R', 'D'] 

以我的經驗,Networkx有着極其寬容的接口,特別是,它將接受範圍廣泛的對象類型作爲節點和邊緣。節點可以是除None以外的任何可哈希對象。

我能想到的唯一的事情可能會導致您在您的問與答提出的錯誤是你裝箱圖形之後或許你直接操縱的圖形對象(字典, * G *),您不應該做 - 有很多訪問器方法。

+0

說實話,我不知道我的問題究竟是什麼,但我愚弄了對象,並最終讓它正常工作。感謝您經過深思熟慮的迴應。它讓我想到了:) – Trim 2010-11-18 02:44:15

相關問題