可在 networkx 中使用的属性列表

use*_*716 6 python networkx

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

有人可以指出我记录的地方吗?

谢谢!

Tho*_*ber 5

如果您想要查询图表以获取可能已应用于各个节点的所有可能属性(对于共同创建的图表或随着时间的推移而编辑的图表,这比您想象的更常见),那么以下对我有用:

set(np.array([list(self.graph.node[n].keys()) for n in self.graph.nodes()]).flatten())
Run Code Online (Sandbox Code Playgroud)

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

from itertools import chain
set(chain(*[(ubrg.graph.node[n].keys()) for n in ubrg.graph.nodes()]))
Run Code Online (Sandbox Code Playgroud)

  • 这是最普通的:`set([k for n in g.nodes for k in g.nodes[n].keys()])`。我不明白为什么同样的方法对我获取边缘属性不起作用;这适用于节点或边。 (7认同)

Joe*_*oel 3

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

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'
Run Code Online (Sandbox Code Playgroud)

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

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'
Run Code Online (Sandbox Code Playgroud)

类似地还有一个nx.get_edge_attributesnx.set_edge_attributes

更多信息请参见networkx 教程。大约在本页中间的标题“节点属性”和“边属性”下。set...attributes和的具体文档可以“属性”下get...attributes找到。