NetworkX如何访问节点对象的属性
我创建了一个这样的示例图:
class myObject(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
one = myObject("ONE")
Graph = nx.Graph()
Graph.add_node(one)
在这种情况下,我怎么才能访问对象“one”的属性呢?我发现如果把这个对象作为节点的属性添加进去,我就可以访问它。不过,用
In [1]: Graph[one]
Out[1]: {}
或者比如说
In [2]: print Graph[one]
{}
来打印名字是行不通的。
我也知道我可以遍历由
Graph.nodes()
返回的列表,但我在想有没有更好的方法来做到这一点。
1 个回答
1
你可以直接查看你的对象'one'
In [1]: import networkx as nx
In [2]: %paste
class myObject(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
one = myObject("ONE")
Graph = nx.Graph()
Graph.add_node(one)
## -- End pasted text --
In [3]: print(one)
ONE
在NetworkX中,你可以通过使用节点属性来存储任意数据,这样可能会更简单。你甚至可以把一个自定义对象作为属性添加进去。
In [4]: G = nx.Graph()
In [5]: G.add_node("ONE", color='red')
In [6]: G.node["ONE"] # dictionary of attributes
Out[6]: {'color': 'red'}
In [7]: G.add_node("ONE",custom_object=one)
In [8]: G.node["ONE"] # dictionary of attributes
Out[8]: {'color': 'red', 'custom_object': <__main__.myObject at 0x988270c>}