发布于2020-01-15 21:31 阅读(1758) 评论(0) 点赞(30) 收藏(0)
我有一个包含自循环的NetworkX MultiDiGraph。根据文档,这是MultiDiGraph的有效属性。
MultiDiGraph保存有向边。允许自循环。
但是,当我尝试使用从MultiDiGraph中删除自环时MG.remove_edges_from(MG.selfloop_edges())
,会生成以下警告:
---------------------------------------------------------------------------
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
我是否从MultliDiGraph删除自环的过程中缺少某些东西,或者这是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())
此方法可与DiGraph一起使用,如下所示:
# 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()
图形上的自环边缘上有一个迭代器(更确切地说是生成器),并且通过删除边缘,您可以在迭代过程中更改迭代器的边缘。
根据文档:
参数:ebunch(边缘元组的列表或容器)-...
这意味着该ebunch
参数应该是一个容器,同时MG.selfloop_edges()
返回一个生成器。您可以在此处详细了解两者之间的区别。
可以通过传递list(MG.selfloop_edges())
给MG.remove_edges_from
(而不是MG.selfloop_edges()
直接传递)来解决此问题。
作者:黑洞官方问答小能手
链接:https://www.pythonheidong.com/blog/article/223745/c0c1ac894e93e9163d89/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!