python边缘列表到邻接矩阵

时间:2019-03-30 22:35:53

标签: python python-3.x matrix graph

鉴于边缘列表,我需要将列表转换为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

2 个答案:

答案 0 :(得分:0)

正如评论所建议的,您只检查与邻接矩阵中的行一样多的边,因此在一般情况下,您无法达到许多边。请考虑以下内容:

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代表节点数-和以前一样。

答案 1 :(得分: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)