Networkx copy clarification

放肆的年华 提交于 2019-12-13 13:52:42

问题


According the doc, it appears that the networkx.copy method does a deep copy of the graph. I'm most concerned about the statement

This makes a complete copy of the graph including all of the node or edge attributes.

Is this suggesting that it makes a copy of what the nodes contain as well? For example if I have the following

class NodeContainer(object):

    def __init__(self, stuff):
        self.stuff = stuff

    # ..other class stuff


g = networkx.DiGraph():

n1 = NodeContainer(stuff1)
n2 = NodeContainer(stuff2)

g.add_edge(n1,n2)

g2 = g.copy()

In the g2 = g.copy() line is it making deep copies of the NodeContainer objects as well? If so, is there an existing implementation of a shallow copy? I have not been able to find one. I ask because I currently have use to create a copy a graph that I will edit (remove nodes from) but not change the actual nodes themselves. So I don't need a deep copy in that sense, just a representation of the graph structure.

EDIT: If possible I'd also like to do a shallow reverse()


回答1:


You can make a shallow copy by using the class constructor. E.g. for graphs,

In [1]: import networkx as nx

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

In [3]: G.add_edge(1,2,l=['a','b','c'])

In [4]: H = nx.Graph(G) # shallow copy

In [5]: H[1][2]['l']
Out[5]: ['a', 'b', 'c']

In [6]: H[1][2]['l'].append('d')

In [7]: H[1][2]['l']
Out[7]: ['a', 'b', 'c', 'd']

In [8]: G[1][2]['l']
Out[8]: ['a', 'b', 'c', 'd']


来源:https://stackoverflow.com/questions/29854387/networkx-copy-clarification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!