简体   繁体   English

尝试在Python中将邻接表转换为邻接矩阵

[英]Trying to convert adjacency list to adjacency matrix in Python

I'm struggling to work out how to effectively implement this, even though I know what I'm doing wrong. 尽管我知道自己做错了什么,但我仍在努力找出如何有效实施此操作的方法。 I'm trying to get my code to read an adjacency list for example an undirected, weighted graph: 我试图让我的代码读取一个邻接表,例如一个无向的加权图:

[(1,5)], [(0,5), (2,7)], [(1,7)] [(1,5)],[(0,5),(2,7)],[(1,7)]

And then convert that to an adjacency matrix, which would return: 然后将其转换为邻接矩阵,该矩阵将返回:

[0, 5, inf], [5, 0, 7], [inf, 7, 0] [0,5,inf],[5,0,7],[inf,7,0]

The code below however returns [0, 5, inf], [5, inf, 0, inf, 7], [inf, 7, 0], and I know why this is. 但是下面的代码返回[0,5,inf],[5,inf,0,inf,7],[inf,7,0],我知道为什么会这样。 However, I only want to append 'inf' to the adjacency matrix in cases like [0, 5, inf] because 0 is not adjacent to 2 and thus its weight is 'inf'. 但是,我只想在[0,5,inf]之类的情况下将'inf'附加到邻接矩阵中,因为0与2不相邻,因此其权重为'inf'。 What's the best solution? 最好的解决方案是什么?

def adjacency_matrix(graph_string):
    adj_list = adjacency_list(graph_string)
    n = len(adj_list)
    adj_mat = [[] for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if j == i:
                adj_mat[i].append(0)
            else:
                for neighbour, weight in adj_list[i]:
                    if j == neighbour:
                        adj_mat[i].append(weight)
                        break
                    elif j != neighbour:
                        adj_mat[i].append(float('inf'))
    return adj_mat

The problem seems to be in the elif part 问题似乎出在elif部分

elif j != neighbour:
    adj_mat[i].append(float('inf'))

Because you only want to fill the inf for the missing edges. 因为您只想为缺少的边缘填充inf Using condition elif j < neighbour would be correct if you have your adj_list sorted. 如果对adj_list排序,则使用条件elif j < neighbour是正确的。

However, a better solution would be initializing the adjacency matrix with zero diagonal and inf values elsewhere. 但是,更好的解决方案是在其他地方用对角线和inf值为零初始化邻接矩阵。 And only filling the weights from adjacency list. 并且仅填充邻接列表中的权重。 This way you avoid thinking about non-edges. 这样您就可以避免考虑非边缘。

Here is a short example how that could be implemented using numpy . 这是一个简短的示例,如何使用numpy来实现。

import numpy as np

def adj_list_to_matrix(adj_list):
    n = len(adj_list)
    adj_matrix = np.nan * np.ones((n,n))
    np.fill_diagonal(adj_matrix,0)

    for i in range(n):
        for j, w in adj_list[i]:
            adj_matrix[i,j] = w
    return adj_matrix

Usage: 用法:

adj_list = [(1,5)], [(0,5), (2,7)], [(1,7)]
adj_list_to_matrix(adj_list)

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

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