我正在与networkx一起工作,但无法找到有关边缘或节点可用属性的列表。 我不感兴趣的是已经分配了哪些属性,而是在创建或编辑节点或边缘时可以设置/更改哪些属性。
有人能指出这个文档的位置吗?
谢谢!
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'
你可以使用字典来定义一些属性,然后用 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'
nx.get_edge_attributes
和nx.set_edge_attributes
。更多信息可以在networkx教程的这里找到:这里,在页面的中间位置下方分别是“Node Attributes”和“Edge Attributes”两个小标题。有关set...attributes
和get...attributes
的具体文档可以在此处的“Attributes”章节中找到。# simple version
node_attr = {k for node in GRAPH.nodes for k in GRAPH.nodes[node].keys()}
# efficient version: 3X faster
node_attr = {k for attr_dict in GRAPH.nodes.data()._nodes.values() for k in attr_dict.keys()}
nx.subgraph_view(G, filter_node= lambda n : n in nodes).edges.data(attr)
set([k for n in g.nodes for k in g.nodes[n].keys()])
。我无法理解为什么同样的方法不能用于获取边缘属性;这个方法适用于节点或边缘。 - snooze_bear