Python读取网络(图)边列表数据进而转化为邻接矩阵
时间:2020-12-10 23:22:37
收藏:0
阅读:252
import networkx as nx
G = nx.Graph()
path = ‘./edge_list.txt‘
edge_list = []
node_set = set() #集合的特性就是元素不会重复,互异的
with open(path, ‘r‘) as f:
for line in f:
cols = line.strip().split(‘ ‘)
y1=int(cols[0])
y2=int(cols[1])
node_set.add(y1)
node_set.add(y2)
edge = (y1,y2) #元组代表一条边
edge_list.append(edge)
G.add_nodes_from(range(1,len(node_set)+1)) #节点序号从1开始编号
G.add_edges_from(edge_list)
#A = nx.to_numpy_matrix(G)
A = nx.adjacency_matrix(G).todense()
print(A)
示例:
连边数据:注意连边数据最后的空行一定要删掉,否则会报错
输出的邻接矩阵:
原文:https://www.cnblogs.com/yxtz271828/p/14117821.html
评论(0)