Python边缘列表转邻接矩阵

3

给定一张边列表,我需要在Python中将该列表转换为邻接矩阵。我已经非常接近了,但是我无法弄清楚我的错误在哪里。我的思路有什么问题呢?

E= [[0, 0], [0, 1], [1, 0], [1, 1]]

nmax = max(E)
nmax2 =max(nmax)

m = []
for i in range(nmax2+1):
    row = []
    for j in range(nmax2+1):
         if [i,j]== E[i]:
               row.append(1)
         else:
               row.append(0)
    m.append(row)

 print(m)

我期望的结果应该是: 1 1 1 1
但我的代码输出结果是: 1 0 0 0

1
E[i] 的最大值为 E[1],因为 i 的取值范围只有从 0 到 1。所以你永远不会到达 [1, 0] 和 [1, 1]。 - Sheldore
2个回答

3
正如评论所建议的那样,您只检查了与邻接矩阵中相同数量的行的边缘,因此在一般情况下未能到达许多边缘。请考虑改用以下方法:
E = [[0, 0], [0, 1], [1, 0], [1, 1]]

# nodes must be numbers in a sequential range starting at 0 - so this is the
# number of nodes. you can assert this is the case as well if desired 
size = len(set([n for e in E for n in e])) 
# make an empty adjacency list  
adjacency = [[0]*size for _ in range(size)]
# populate the list for each edge
for sink, source in E:
    adjacency[sink][source] = 1

>>> print(adjacency)
>>> [[1, 1], [1, 1]]

如果你想以简洁为代价获得清晰度:

adjacency = [[1 if [i, j] in set(map(tuple, E)) else 0 for j in range(size)] for i in range(size)]

size 表示节点数量 - 与之前一样。


0

我相信以下代码更简洁且能够完成任务

    E= [[0, 0], [0, 1], [1, 0], [1, 1]]
    size = max(max(E))+1
    r = [[0 for i in range(size)] for j in range(size)]
    for row,col in E:
        r[row][col] = 1
    print(r)    

在邻接矩阵中,维度总是正方形的 - 这通常不正确。 - modesitt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接