[英]Generate adjacency matrix from a list, where adjacency means equal elements
I have a list like this: 我有一个这样的列表:
lst = [0, 1, 0, 5, 0, 1]
I want to generate an adjacency matrix: 我想生成一个邻接矩阵:
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.]])
where out[i,j] = 1 if lst[i]==lst[j]
其中out[i,j] = 1 if lst[i]==lst[j]
Here is my code with two for loops: 这是我的代码,有两个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
But I feel there should be a way to improve this. 但我觉得应该有办法改善这一点。 Any suggestion? 有什么建议吗?
Use broadcasted comparison
- 使用broadcasted comparison
-
np.equal.outer(lst, lst).astype(int) # or convert to float
Sample run - 样品运行 -
In [787]: lst = [0, 1, 0, 5, 0, 1]
In [788]: np.equal.outer(lst, lst).astype(int)
Out[788]:
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]])
Or convert to array and then manually extend to 2D
and compare - 或者转换为数组,然后手动扩展到2D
并进行比较 -
In [793]: a = np.asarray(lst)
In [794]: (a[:,None]==a).astype(int)
Out[794]:
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]])
While the suggestion from @Divakar is very good I will leave this here as a solution without numpy. 虽然来自@Divakar的建议非常好,但我会把它留在这里作为一个没有numpy的解决方案。
lst = [0, 1, 0, 5, 0, 1]
print([[1 if x==y else 0 for x in lst ] for y in lst])
Also for large lists, the accepted solution is much faster. 同样对于大型列表,接受的解决方案要快得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.