可在networkx中使用的属性列表

2024-05-07 12:03:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用networkx,在任何地方都找不到边或节点的可用属性列表。我对已经指定的属性不感兴趣,但对创建或编辑节点或边时可以设置/更改的属性感兴趣

有人能告诉我这是在哪里记录的吗

谢谢


Tags: networkx编辑列表属性节点地方记录感兴趣
2条回答

如果要查询一个图,查找可能已应用于各个节点的所有可能属性(这对于公共创建的图或随时间编辑的图来说,比您可能想象的更常见),那么下面为我提供了一些技巧:

set(np.array([list(self.graph.node[n].keys()) for n in self.graph.nodes()]).flatten())

这将返回所有可能的属性名称,其中有属于图形节点的值。我在这里导入了numpy as np是为了使用np.flatten来获得(相对)性能,但我确信有各种各样的普通python替代方法(例如,如果需要避免numpy,请尝试以下itertools.chain方法)

from itertools import chain
set(chain(*[(ubrg.graph.node[n].keys()) for n in ubrg.graph.nodes()]))

创建许多边或节点属性时,可以指定这些属性。由你决定他们的名字

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'

或者,您可以使用dict来使用nx.set_node_attributes定义某些属性,并为使用nx.get_node_attributes定义特定属性的所有节点创建dict

tmpdict = {1:'green', 2:'blue'}
nx.set_node_attributes(G,'color', tmpdict)
colorDict = nx.get_node_attributes(G,'color')
colorDict
#{1: 'green', 2: 'blue', 'extranode': 'yellow'}
colorDict[2]
#'blue'

类似地,还有nx.get_edge_attributesnx.set_edge_attributes

更多信息请参见networkx教程中的here。大约在本页的一半,标题为“节点属性”和“边缘属性”。有关set...attributesget...attributes的具体文档可以在here的“属性”下找到

相关问题 更多 >