import networkx as nx
G=nx.Graph()
G.add_edge(1,2,weight=5) #G now has nodes 1 and 2 with an edge
G.edges()
#[(1, 2)]
G.get_edge_data(2,1) #note standard graphs don't care about order
#{'weight': 5}
G.get_edge_data(2,1)['weight']
#5
G.add_node('extranode',color='yellow', age = 17, qwerty='dvorak', asdfasdf='lkjhlkjh') #nodes are now 1, 2, and 'extranode'
G.node['extranode']
{'age': 17, 'color': 'yellow', 'qwerty': 'dvorak', 'asdfasdf': 'lkjhlkjh'}
G.node['extranode']['qwerty']
#'dvorak'
如果要查询一个图,查找可能已应用于各个节点的所有可能属性(这对于公共创建的图或随时间编辑的图来说,比您可能想象的更常见),那么下面为我提供了一些技巧:
这将返回所有可能的属性名称,其中有属于图形节点的值。我在这里导入了
numpy as np
是为了使用np.flatten
来获得(相对)性能,但我确信有各种各样的普通python替代方法(例如,如果需要避免numpy,请尝试以下itertools.chain
方法)创建许多边或节点属性时,可以指定这些属性。由你决定他们的名字
或者,您可以使用dict来使用
nx.set_node_attributes
定义某些属性,并为使用nx.get_node_attributes
定义特定属性的所有节点创建dict类似地,还有
nx.get_edge_attributes
和nx.set_edge_attributes
更多信息请参见networkx教程中的here。大约在本页的一半,标题为“节点属性”和“边缘属性”。有关
set...attributes
和get...attributes
的具体文档可以在here的“属性”下找到相关问题 更多 >
编程相关推荐