代码:
import numpy as np
import itertools
import scipy.sparse as sp
edge_index=[] # 建立一个空列表
dst = {2:[5,6,9,8,8],3:[9,8,8],6:[5,9,8]} # 边的信息
for i, j in dst.items(): # 格式为 {index:[index_of_neighbor_nodes]}
edge_index.extend([i, v] for v in j)
edge_index.extend([v, i] for v in j)
print(edge_index)
print(sorted(edge_index))
edge_index = list(k for k, _ in itertools.groupby(sorted(edge_index))) # 去除重复值
print(edge_index)
print(np.array(edge_index)[:, 1])
print(np.array(edge_index)[:, 0])
edge_index = np.array(edge_index)
adjacency = sp.coo_matrix((np.ones(len(edge_index)),
(edge_index[:, 0], edge_index[:, 1])),
shape=(10, 10), dtype="float32") # shape=(10, 10) 因为 dst最大值为9,所以为10
print(adjacency)
输出:
D:\Anaconda3\python.exe D:/0_me_python/1.py
[[2, 5], [2, 6], [2, 9], [2, 8], [2, 8], [5, 2], [6, 2], [9, 2], [8, 2], [8, 2], [3, 9], [3, 8], [3, 8], [9, 3], [8, 3], [8, 3], [6, 5], [6, 9], [6, 8], [5, 6], [9, 6], [8, 6]]
[[2, 5], [2, 6], [2, 8], [2, 8], [2, 9], [3, 8], [3, 8], [3, 9], [5, 2], [5, 6], [6, 2], [6, 5], [6, 8], [6, 9], [8, 2], [8, 2], [8, 3], [8, 3], [8, 6], [9, 2], [9, 3], [9, 6]]
[[2, 5], [2, 6], [2, 8], [2, 9], [3, 8], [3, 9], [5, 2], [5, 6], [6, 2], [6, 5], [6, 8], [6, 9], [8, 2], [8, 3], [8, 6], [9, 2], [9, 3], [9, 6]]
[5 6 8 9 8 9 2 6 2 5 8 9 2 3 6 2 3 6]
[2 2 2 2 3 3 5 5 6 6 6 6 8 8 8 9 9 9]
(2, 5) 1.0
(2, 6) 1.0
(2, 8) 1.0
(2, 9) 1.0
(3, 8) 1.0
(3, 9) 1.0
(5, 2) 1.0
(5, 6) 1.0
(6, 2) 1.0
(6, 5) 1.0
(6, 8) 1.0
(6, 9) 1.0
(8, 2) 1.0
(8, 3) 1.0
(8, 6) 1.0
(9, 2) 1.0
(9, 3) 1.0
(9, 6) 1.0
Process finished with exit code 0