MultiGraph.remove_nodes_from#
- MultiGraph.remove_nodes_from(nodes)#
移除多个节点。
- 参数:
- nodes可迭代容器
一个节点容器(列表、字典、集合等)。如果容器中的节点不在图中,则会被静默忽略。
另请参阅
注意
当从正在更改的图的迭代器中移除节点时,会引发
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.Graph([(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))