Graph.remove_nodes_from#

Graph.remove_nodes_from(nodes)[source]#

移除多个节点。

参数:
nodes可迭代容器

一个包含节点的容器(list、dict、set等)。如果容器中的节点不在图中,则会默默忽略。

另请参阅

remove_node

注意

当从您正在更改的图的迭代器中移除节点时,会引发一个 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))