繁体   English   中英

python边缘列表到邻接矩阵

[英]python edge list to adjacency matrix

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

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

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 - 和以前一样。

我在下面是更清洁,并完成工作

    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)    

暂无
暂无

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

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