程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

从NetworkX MultiDiGraph删除自环会导致运行时错误

发布于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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

30 0
收藏该文
已收藏

评论内容:(最多支持255个字符)