You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NetworkX MultiGraph移除指定边后仍存在的问题及批量删除需求

NetworkX MultiGraph 删除指定属性边失败的问题解决

我构建了如下的NetworkX MultiGraph,尝试移除其中所有asset为"a15"的边,但执行后打印所有边数据时发现该边仍存在,请问问题出在哪里?如何正确删除所有asset标签为"a15"的边?

import networkx as nx

G = nx.MultiGraph()
G.add_edge(17, 12, nm=5, asset="a12")
G.add_edge(14, 13, nm=15, asset="a13")
G.add_edge(17, 13, nm=5, asset="a14")
G.add_edge(27, 110, nm=15, asset="a15")
G.add_edge(27, 110, nm=5, asset="a19")
G.add_edge(27, 280, nm=5, asset="a19")

# remove asset a15
for a, b, attributes in G.edges(data=True):
    if attributes["asset"]=="a15": 
        lst=[(a, b)]
G.remove_edges_from(lst)

#print the current edges in the graph
for cc in nx.connected_components(G):
   print("asset", list(nx.get_edge_attributes(G.subgraph(cc), "asset").values()))

输出结果:

asset ['a12', 'a14', 'a13']
asset ['a19', 'a15']

问题原因

你的代码存在两个关键问题:

  • 边收集逻辑错误:循环中每次找到符合条件的边时,都会重新给lst赋值为[(a,b)],如果存在多条asset为"a15"的边,lst只会保留最后一条;即使只有一条,这种收集方式也无法精准定位到MultiGraph中的特定边。
  • 删除方式错误:remove_edges_from([(a,b)])会删除节点a和b之间的所有边,且你的代码中该操作未生效(可能是遍历与删除的时机冲突或变量作用域隐性问题),同时这也不符合你"仅删除asset为'a15'的边"的需求,会误删同节点对的其他边。

在NetworkX的MultiGraph中,单靠节点对(u,v)无法唯一标识一条边,每条边还有一个唯一的key值(默认从0开始递增),必须通过(u, v, key)的组合才能精准定位并删除特定边。


正确解决方案

修改代码,先收集所有asset为"a15"的边的完整标识符(包含key),再批量删除:

import networkx as nx

G = nx.MultiGraph()
G.add_edge(17, 12, nm=5, asset="a12")
G.add_edge(14, 13, nm=15, asset="a13")
G.add_edge(17, 13, nm=5, asset="a14")
G.add_edge(27, 110, nm=15, asset="a15")
G.add_edge(27, 110, nm=5, asset="a19")
G.add_edge(27, 280, nm=5, asset="a19")

# 收集所有asset为a15的边(包含key)
edges_to_remove = []
for u, v, key, attrs in G.edges(keys=True, data=True):
    if attrs["asset"] == "a15":
        edges_to_remove.append((u, v, key))

# 删除指定边
G.remove_edges_from(edges_to_remove)

# 打印当前边的asset属性
for cc in nx.connected_components(G):
    subgraph = G.subgraph(cc)
    print("asset", list(nx.get_edge_attributes(subgraph, "asset").values()))

执行后输出:

asset ['a12', 'a14', 'a13']
asset ['a19', 'a19']

可以看到,所有asset为"a15"的边已被成功删除,同节点对的"a19"边和其他边都被保留。

内容的提问来源于stack exchange,提问作者user20321911

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:49:58