gpt4 book ai didi

networkx - 如何复制而不是深度复制 networkx 图?

转载 作者:行者123 更新时间:2023-12-03 09:13:35 26 4
gpt4 key购买 nike

我想在函数调用 d(n) 之前比较 networkx.Graph 对象 n 的状态(有副作用)之后与国家合作。

有一些可变的对象节点属性,例如 n.node[0]['attribute'],我想对其进行比较。

显然,

before = n
d()
after = n
assert id(before.node[0]['attribute']) == id(after.node[0]['attribute'])

取得了微不足道的成功,因为

before == after

但如果我设置 before=n.copy(),则会进行深层复制,因此 id(before.node[0]['attribute']) != id (after.node[0]['属性'])。如何在不复制所有节点属性对象的情况下获取 Graph 对象的副本?

最佳答案

调用copy方法会产生深层复制。新图的所有属性都是原始图的副本。调用构造函数(例如Graph(G))会给出一个浅拷贝,其中复制图结构,但数据属性引用原始图中的数据属性。

来自copy方法文档

All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want.

Deepcopy -- The default behavior is a "deepcopy" where the graph structure as well as all data attributes and any objects they might contain are copied. The entire graph object is new so that changes in the copy do not affect the original object.

Data Reference (Shallow) -- For a shallow copy (with_data=False) the graph structure is copied but the edge, node and graph attribute dicts are references to those in the original graph. This saves time and memory but could cause confusion if you change an attribute in one graph and it changes the attribute in the other.

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_node(1, color=['red'])

In [4]: G_deep = G.copy()

In [5]: G_deep.node[1]['color'].append('blue')

In [6]: list(G.nodes(data=True))
Out[6]: [(1, {'color': ['red']})]

In [7]: list(G_deep.nodes(data=True))
Out[7]: [(1, {'color': ['red', 'blue']})]

In [8]: G_shallow = nx.Graph(G)

In [9]: G_shallow.node[1]['color'].append('blue')

In [10]: list(G.nodes(data=True))
Out[10]: [(1, {'color': ['red', 'blue']})]

In [11]: list(G_shallow.nodes(data=True))
Out[11]: [(1, {'color': ['red', 'blue']})]

关于networkx - 如何复制而不是深度复制 networkx 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com