当想要用remove_edges_from()移除某一个节点的所有相关边时:
ba = nx.path_graph(4)
edges=ba.edges([1]) #获取节点的所有相关边
ba.remove_edges_from(edges)
出现如以下报错RuntimeError: dictionary changed size during iteration:
Traceback (most recent call last):
File "D:/lab/dql_lab/dql_sup_dismantle/unknown.py", line 122, in <module>
ba.remove_edges_from(e)
File "I:\about_python\Anaconda3\envs\maddpg\lib\site-packages\networkx\classes\graph.py", line 1035, in remove_edges_from
for e in ebunch:
File "I:\about_python\Anaconda3\envs\maddpg\lib\site-packages\networkx\classes\reportviews.py", line 775, in __iter__
for nbr, dd in nbrs.items():
RuntimeError: dictionary changed size during iteration
查找手册发现出错原因是:
Warning: we protect the graph data structure by making G.edges
a
read-only dict-like structure. However, you can assign to attributes
in e.g. G.edges[1, 2]
. Thus, use 2 sets of brackets to add/change
data attributes: G.edges[1, 2]['weight'] = 4
因此需要把edges转为list类型:
ba = nx.path_graph(4)
edges=list(ba.edges([1]))
ba.remove_edges_from(edges)
运行成功