2017-05-12 57 views

回答

1

nx.adjacency_matrix返回SciPy稀疏(鄰接)矩陣。爲了得到一個密集(NumPy的)矩陣,調用它的todense方法:

import networkx as nx 

G = nx.path_graph(4, create_using=nx.DiGraph()) 
m = nx.adjacency_matrix(G) 
print(m) 
# (0, 1) 1 
# (1, 2) 1 
# (2, 3) 1 

print(m.todense()) 
# [[0 1 0 0] 
# [0 0 1 0] 
# [0 0 0 1] 
# [0 0 0 0]] 

或者,撥打nx.to_numpy_matrix

print(nx.to_numpy_matrix(G)) 
# [[ 0. 1. 0. 0.] 
# [ 0. 0. 1. 0.] 
# [ 0. 0. 0. 1.] 
# [ 0. 0. 0. 0.]] 

要獲取列表的純Python列表,請撥打NumPy的矩陣的tolist方法:

print(m.todense().tolist()) 
# [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]]