DiGraph.remove_nodes_from#
- DiGraph.remove_nodes_from(nodes)[source]#
移除多个节点。
- 参数:
- nodes可迭代容器
一个节点容器(list, dict, set 等)。如果容器中的节点不在图中,则会静默忽略。
另请参阅
注意事项
从正在迭代的图上移除节点时,会引发
RuntimeError
,消息为:RuntimeError: dictionary changed size during iteration
。这是因为图的底层字典在迭代期间被修改。为了避免此错误,请将迭代器求值到一个单独的对象中,例如使用list(iterator_of_nodes)
,然后将此对象传递给G.remove_nodes_from
。示例
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []
如果使用迭代器修改同一图,则应对迭代器进行求值
>>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)]) >>> # this command will fail, as the graph's dict is modified during iteration >>> # G.remove_nodes_from(n for n in G.nodes if n < 2) >>> # this command will work, since the dictionary underlying graph is not modified >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))