我试图使用 igraph 在 python 中编写代码,当我尝试使用 while 循环添加边缘时出现此错误
while(i<k)
g.add_vertices(theInts[i])
i=i+1
g.add_edges([(theInts[i-1],theInts[i])])
我认为索引可能是一个问题,所以我还包含了一个 if 语句,但这似乎不是问题。
请帮忙!!!
最佳答案
我认为这一切都取决于 g
的顶点。如果您从空的 g
开始,则只有顶点 0
,因此如果您尝试使用两个不同的顶点调用 add_edges
,这是行不通的。您必须添加更多顶点。当然,这一切都取决于您的图形在循环之前的样子以及 i
是什么。
您可以使用 print
显示有关图表的一些简短信息。例如,
>>> import igraph
>>> graph = igraph.Graph()
>>> print graph
Undirected graph (|V| = 1, |E| = 0)
如果i
从0开始,那么第一次时您将不会在循环中添加任何顶点。因此,当您尝试添加边时,您正在尝试添加到不存在的顶点。
>>> graph.add_vertices(0)
<igraph.Graph object at 0xcea850>
>>> print graph
Undirected graph (|V| = 1, |E| = 0)
>>> graph.add_edges([(0, 1)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
igraph.core.InternalError: Error at type_indexededgelist.c:245: cannot add edges, Invalid vertex id
如果这不是问题,请尝试打印边缘并查看它们是否与您想要的相符。
>>> graph.add_vertices(5)
<igraph.Graph object at 0xcea850>
>>> print graph
Undirected graph (|V| = 6, |E| = 3)
>>> graph.add_edges([(1, 1), (2, 3), (3, 5)])
<igraph.Graph object at 0xcea850>
>>> graph.get_edgelist()
[(1, 1), (2, 3), (3, 5)]
此外,拥有完整的 TraceBack 可能会更有帮助。
编辑:根据您的评论
所以你是说你有这样的结构:
>>> graph = igraph.Graph()
>>> print graph
Undirected graph (|V| = 1, |E| = 0)
您只想添加顶点 2 吗?我不确定你能用 igraph 做到这一点。似乎必须按顺序排列每个顶点。您可以检查是否有顶点,然后在必要时添加它们,请记住这些图是从 0 开始的。像这样的东西。
>>> vertices = 1, 2, 13, 4, 21, 5
>>> map_graph = igraph.Graph()
>>> print map_graph
Undirected graph (|V| = 1, |E| = 0)
>>> map_graph.add_vertices(max(vertices))
<igraph.Graph object at 0xceaa50>
>>> print map_graph
Undirected graph (|V| = 22, |E| = 0)
>>> map(map_graph.add_edges, zip(vertices, vertices[1:]))
[<igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>]
>>> print map_graph
Undirected graph (|V| = 22, |E| = 5)
>>> map_graph.get_edgelist()
[(1, 2), (2, 13), (4, 13), (4, 21), (5, 21)]
或者,如果您不喜欢 map ,可以将其循环播放。
>>> vertices = 1, 2, 13, 4, 21, 5
>>> loop_graph = igraph.Graph()
>>> print loop_graph
Undirected graph (|V| = 1, |E| = 0)
>>> loop_graph.add_vertices(max(vertices))
<igraph.Graph object at 0xcea950>
>>> print loop_graph
Undirected graph (|V| = 22, |E| = 0)
>>> for pair in zip(vertices, vertices[1:]):
... loop_graph.add_edges(pair)
...
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
>>> print loop_graph
Undirected graph (|V| = 22, |E| = 5)
>>> loop_graph.get_edgelist()
[(1, 2), (2, 13), (4, 13), (4, 21), (5, 21)]
不过,可能有更好的方法来做到这一点。如果这不是您正在寻找的内容,请使用更多详细信息和一些实际代码来编辑您的原始问题。
关于python - 无法添加边,IGraph 中的顶点 ID 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10055246/