图论算法(三):networkx 添加属性

属性(如权重,标签,颜色或任何您喜欢的Python对象)可以附加到节点或连边中。每个节点和连边都可以在关联的属性字典中保存键/值属性对(键必须是可散列的)。 默认情况下,这些属性是空的,但可以使用G.node和G.edge的属性字典来添加或更改属性。

1. 添加节点属性
使用add_node()添加节点属性

import networkx as nx

G = nx.Graph() # new graph

G.add_node(1, attr1 = 'this_is_a_node_attribute')

print G.nodes()
print G.nodes[1] # print nodes
print G.nodes(data=True) # print nodes

这里写图片描述

2. 查看节点属性
使用get_node_attributes()查看节点属性

import networkx as nx

# new graph
G = nx.Graph()

# add node
G.add_node('a', color = 'blue')
G.add_node('b', color = 'red')
G.add_node('c', color = 'black')
G.add_node('d', color = 'yellow')
G.add_node('e', color = 'red')
G.add_node('f', color = 'blur')
G.add_node('g', color = 'yellow')

# attribute of a node
color = nx.get_node_attributes(G, 'color')
print color['a']

这里写图片描述

3. 添加连边属性
使用add_edge()添加连边属性

import networkx as nx

G = nx.Graph() # new graph

G.add_node(1)
G.add_node(2)

G.add_edge(1, 2, attr2 = 'this_is_a_edge_attribute' )

print G.edges() # print edges
print G.edges(data=True) # print edges
print type(G)

这里写图片描述

4. 查看连边属性
使用get_edge_attributes()添加连边属性

import networkx as nx

# new graph
G = nx.Graph()

# add node
G.add_node('a', color = 'blue')
G.add_node('b', color = 'red')
G.add_node('c', color = 'black')
G.add_node('d', color = 'yellow')
G.add_node('e', color = 'red')
G.add_node('f', color = 'blur')
G.add_node('g', color = 'yellow')

# add edge
G.add_edge('a', 'b', mix = 'blue')
G.add_edge('a', 'c', mix = 'grey')

# attribute of an edge
mix = nx.get_edge_attributes(G, 'mix')
print mix['a','c']

这里写图片描述

参考
https://networkx.github.io/documentation/networkx-1.10/tutorial/tutorial.html

你可能感兴趣的:(计算机网络)