我自己的对象使用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我必须添加到我的披萨类中的任何想法吗?

编辑:我的边缘格式正确.我不知道这些对象是否可以作为节点来处理.

解决方法:

如果边和节点各作为一个列表,那么在networkx中构建图形就很简单.鉴于您的问题是在构建图形对象时发生的,也许最好的诊断方法是逐步在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具有一个非常宽松的接口,尤其是它将接受广泛的对象类型作为节点和边.节点可以是除无之外的任何可哈希对象.

我唯一想到的可能会导致您在Q中出现的错误是,也许在创建图表之后,您直接操作了图形对象(dict,* G *),您不应该这样做-大量的访问器方法.

上一篇:networkx学习与使用——(5)节点和边的属性:聚集系数和邻里重叠度


下一篇:在Python中使用networkx绘制二部图