解决nx.remove_edges_from()出现错误

当想要用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)

运行成功

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值