简体   繁体   English

如果边存在于 2 个节点之间则取值为 1 的矩阵,否则取自邻接字典的值为 0

[英]matrix which takes as value 1 if an edge exist between 2 nodes and 0 otherwise from an adjacency dictionary

I have an adjacency dictionary like this:我有一个这样的邻接字典:

{1: {8, 2}, 2: {3}, 5: {9, 7}, 7: {8}, 3: {8, 4}, 4: {5}, 8: {9}, 9: {7}}

My code to do it is :我的代码是:

list = [(1, 2), (2, 3), (5, 7), (5, 9), (7, 8), (3, 4), (4, 5), (5, 7), (7, 8), (8, 9), (9, 7), (1, 8), (3, 8)]

dic = {}
for x, y in list:
    dic.setdefault(x, set()).add(y)
return dic

And I want to produce a matrix which takes as value 1 if an edge exist between 2 nodes and 0 otherwise.我想生成一个矩阵,如果 2 个节点之间存在边,则该矩阵取值为 1,否则为 0。 Here an example of what I want :这是我想要的一个例子:

[0,1,0,0,0,0,0,1,0]
[0,0,1,0,0,0,0,0,0]
[0,0,0,1,0,0,0,1,0]
[0,0,0,0,1,0,0,0,0]
[0,0,0,0,0,0,1,0,1]
[0,0,0,0,0,0,0,1,0]
[0,0,0,0,0,0,0,0,1]
[0,0,0,0,0,0,1,0,0]

This is what I want with my adjacency dictionary.这就是我想要的邻接字典。

Thanks in advance提前致谢

here is another solution这是另一个解决方案

import numpy as np
dic = {1: {8, 2}, 2: {3}, 5: {9, 7}, 7: {8}, 3: {8, 4}, 4: {5}, 8: {9}, 9: {7}}
arr = np.zeros((9,9))
for k in dic.keys():
    for v in dic[k]:
        arr[k-1][v-1] = 1
print(arr)

You could do:你可以这样做:

import pprint

lst = [(1, 2), (2, 3), (5, 7), (5, 9), (7, 8), (3, 4), (4, 5), (5, 7), (7, 8), (8, 9), (9, 7), (1, 8), (3, 8)]

dic = {}
for x, y in lst:
    dic.setdefault(x, set()).add(y)

size = max(dic) + 1
result = [[int(j in dic and i in dic[j]) for i in range(1, size)] for j in range(1, size)]

pprint.pprint(result) # just for pretty printing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM