python - 将 networkx 与我自己的对象一起使用

标签 python graph-theory 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 有一个非常宽松的接口(interface),特别是,它会接受范围广泛的对象类型作为节点和边缘。节点可以是除 None 之外的任何可哈希对象。

我能想到的唯一可能导致您在 Q 中出现的错误的是,也许在您创建图表后,您直接操作了图表对象(dict, em> *G*),这是你不应该做的——有很多访问器方法。

关于python - 将 networkx 与我自己的对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4210616/

相关文章:

python - 我如何在 pyspark 应用程序中维护临时字典?

php - C 与 php/asp 连接

algorithm - 给定多个图,找到两个节点之间的最短距离

algorithm - 用于团发现的 Bron-Kerbosch 算法

python - 如何使用 2.0 之前的 networkx 版本读取 pandas dataframe

python - 选择两个数据框列之一作为新列的输入

python - 如何使用 assertRaises() 捕获 "TypeError"

python - 属性错误 : module 'asyncio' has no attribute 'create_task'

python - 为什么中间中心性的 Networkx 输出是错误的?

python - 为什么在Python类的__init__中使用self.foo = self.foo?