Graph.add_edges_from#

Graph.add_edges_from(ebunch_to_add, **attr)[source]#

添加 ebunch_to_add 中的所有边。

参数:
ebunch_to_add边容器

容器中给出的每条边将被添加到图中。边必须以 2 元组 (u, v) 或 3 元组 (u, v, d) 的形式给出,其中 d 是包含边数据的字典。

attr关键字参数, 可选

可以使用关键字参数分配边数据(或标签或对象)。

另见

add_edge

添加一条单独的边

add_weighted_edges_from

添加带权边的便捷方式

备注

添加同一条边两次没有效果,但在添加每个重复边时,任何边数据都将更新。

在 ebunch 中指定的边属性优先于通过关键字参数指定的属性。

当从你正在更改的图上的迭代器添加边时,可能会引发 RuntimeError,并带有消息:RuntimeError: dictionary changed size during iteration。当图的底层字典在迭代期间被修改时,就会发生这种情况。为避免此错误,请将迭代器评估到一个单独的对象中,例如使用 list(iterator_of_edges),然后将此对象传递给 G.add_edges_from

示例

>>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edges_from([(0, 1), (1, 2)])  # using a list of edge tuples
>>> e = zip(range(0, 3), range(1, 4))
>>> G.add_edges_from(e)  # Add the path graph 0-1-2-3

将数据关联到边

>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")

如果使用迭代器修改同一图,请对图上的迭代器进行评估

>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
>>> # Grow graph by one new node, adding edges to all existing nodes.
>>> # wrong way - will raise RuntimeError
>>> # G.add_edges_from(((5, n) for n in G.nodes))
>>> # correct way - note that there will be no self-edge for node 5
>>> G.add_edges_from(list((5, n) for n in G.nodes))