3
我有这样的列表:从列表,其中邻接装置相等的元素生成邻接矩阵
lst = [0, 1, 0, 5, 0, 1]
我要生成邻接矩阵:
out =
array([[ 1., 0., 1., 0., 1., 0.],
[ 0., 1., 0., 0., 0., 1.],
[ 1., 0., 1., 0., 1., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 1., 0., 1., 0., 1., 0.],
[ 0., 1., 0., 0., 0., 1.]])
其中out[i,j] = 1 if lst[i]==lst[j]
这里是我的两个for循环代码:
lst = np.array(lst)
label_lst = list(set(lst))
out = np.eye(lst.size, dtype=np.float32)
for label in label_lst:
idx = np.where(lst == label)[0]
for pair in itertools.combinations(idx,2):
out[pair[0],pair[1]] = 1
out[pair[1],pair[0]] = 1
但我觉得应该有一种方法来改善这一点。任何建议?
它看起来像一个非常整洁的解决方案(+ 1) –