gpt4 book ai didi

python - 从 NetworkX MultiDiGraph 中删除自循环会导致运行时错误

转载 作者:行者123 更新时间:2023-11-28 17:03:54 26 4
gpt4 key购买 nike

我有一个包含自环的 NetworkX MultiDiGraph。根据documentation ,这是 MultiDiGraph 的有效属性。

A MultiDiGraph holds directed edges. Self loops are allowed.

但是当我尝试使用 MG.remove_edges_from(MG.selfloop_edges()) 从 MultiDiGraph 中删除自循环时,生成了以下警告:

---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-13-ff3391f2296f> in <module>()
1 # remove selfloop edges from the graph
----> 2 MG.remove_edges_from(MG.selfloop_edges())

~/Program_Files/miniconda3/envs/py36/lib/python3.6/site-packages/networkx/classes/multigraph.py in remove_edges_from(self, ebunch)
603 []
604 """
--> 605 for e in ebunch:
606 try:
607 self.remove_edge(*e[:3])

~/Program_Files/miniconda3/envs/py36/lib/python3.6/site-packages/networkx/classes/function.py in <genexpr>(.0)
1154 return ((n, n)
1155 for n, nbrs in G.adj.items()
-> 1156 if n in nbrs for d in nbrs[n].values())
1157 else:
1158 return ((n, n) for n, nbrs in G.adj.items() if n in nbrs)

~/Program_Files/miniconda3/envs/py36/lib/python3.6/_collections_abc.py in __iter__(self)
759
760 def __iter__(self):
--> 761 for key in self._mapping:
762 yield self._mapping[key]
763

RuntimeError: dictionary changed size during iteration

在您从 MultiDiGraph 中删除自循环的方式中我是否遗漏了什么或者这是 NetworkX 的错误?

演示意外错误的可重现示例:

import networkx as nx

# create an empty MultiDiGraph
MG = nx.MultiDiGraph()

# add some edges to the graph
MG.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 2), (2, 1), (2, 2)])

# check the edges in the graph
MG.edges()

# remove selfloop edges from the graph
MG.remove_edges_from(MG.selfloop_edges())

此方法与有向图的预期效果一致,如下所示:

# create an empty MultiDiGraph
G = nx.DiGraph()

# add some edges to the graph
G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 2), (2, 1), (2, 2)])

# check the edges in the graph
G.edges
OutEdgeView([(1, 2), (2, 3), (2, 1), (2, 2), (3, 1)])

# remove selfloop edges from the graph
G.remove_edges_from(G.selfloop_edges())

# check the edges in the graph
G.edges()
OutEdgeView([(1, 2), (2, 3), (2, 1), (3, 1)])

最佳答案

问题在于 MG.selfloop_edges() 是图中自循环边上的迭代器(更准确地说是生成器),通过移除边,您在迭代期间更改了迭代器的边。

根据documentation :

Parameters: ebunch (list or container of edge tuples) - ...

这意味着 ebunch 参数应该是一个容器,而 MG.selfloop_edges() 返回一个生成器。您可以阅读更多关于两者之间区别的信息 here .

可以通过将 list(MG.selfloop_edges()) 传递给 MG.remove_edges_from 来解决这个问题(而不是传递 MG.selfloop_edges() 直接)。

关于python - 从 NetworkX MultiDiGraph 中删除自循环会导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com