Logo
Section 1 / 4

网络数据表示

学习如何使用边列表、邻接矩阵和邻接表来表示复杂网络。

导入

网络数据表示

学习如何使用边列表、邻接矩阵和邻接表来表示复杂网络。

...
一个示例网络
1edge_list = [ 2 (node_1, node_2), 3 (node_2, node_3), 4 (node_3, node_4) 5]
1import networkx as nx 2 3edge_list = [ 4 (0, 1), 5 (0, 3), 6 (2, 3), 7 (3, 5), 8 (1, 4) 9] 10 11G = nx.Graph() 12G.add_edges_from(edge_list) 13 14print('节点: ', G.nodes()) 15print('边: ', G.edges())
1import networkx as nx 2 3edge_list = [ 4 (0, 1), 5 (0, 3), 6 (2, 3), 7 (3, 5), 8 (1, 4) 9] 10 11nodes_list = [0, 1, 2, 3, 4, 5, 13] 12 13G = nx.Graph() 14 15# 我们将节点单独添加,而不是与边一起添加 16G.add_nodes_from(nodes_list) 17G.add_edges_from(edge_list) 18 19print('节点: ', G.nodes()) 20print('边: ', G.edges())
...
一个示例网络
1import networkx as nx 2 3edge_list = [ 4 5] 6 7nodes_list = [] 8 9G = nx.Graph() 10G.add_nodes_from(nodes_list) 11G.add_edges_from(edge_list) 12 13print(G.nodes()) 14print(G.edges())

A = \begin{bmatrix} 0& 1 & 0 & 1 & 0 & 0\ 1& 0 & 0 & 0 & 1 & 0\ 0& 0 & 0 & 1 & 0 & 0\ 1& 0 & 1 & 0 & 0 & 1\ 0& 1 & 0 & 0 & 0 & 0\ 0& 0 & 0 & 1 & 0 & 0 \end{bmatrix}

1import networkx as nx 2import numpy as np 3 4adjacency_matrix = [[0., 1., 0., 1., 0., 0.], 5 [1., 0., 0., 0., 1., 0.], 6 [0., 0., 0., 1., 0., 0.], 7 [1., 0., 1., 0., 0., 1.], 8 [0., 1., 0., 0., 0., 0.], 9 [0., 0., 0., 1., 0., 0.]] 10 11G = nx.from_numpy_array(np.array(adjacency_matrix)) 12 13print(G.nodes()) 14print(G.edges())
...
示例网络
1import networkx as nx 2import numpy as np 3 4adjacency_matrix = [] 5 6# 现在创建图 7G = 8 9print(G.nodes()) 10print(G.edges())
...
邻接表表示
1import networkx as nx 2 3adjacency_list = ["1 2 3 4", "2 3 5", "3 4 5", "4 2", "5 1"] 4 5G = nx.parse_adjlist(adjacency_list, nodetype=int, create_using=nx.DiGraph()) 6 7print('节点: ', G.nodes()) 8print('边: ', G.edges())
1G = nx.parse_adjlist(adjacency_list, nodetype=int, create_using=nx.Graph())
...
练习用图
1import networkx as nx 2 3# 定义你的邻接表 4adjacency_list = [] 5 6# 现在创建图 7G = 8 9print(G.edges())

图论与复杂网络导论

NetworkX 概述