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) –