Adjacency matrix in Python

后端 未结 4 739
我寻月下人不归
我寻月下人不归 2021-02-06 03:43

I cannot find any clear explanation as to how to create an adjacency matrix in Python, with weights taken into consideration. I assume it should be relatively simple to create.<

4条回答
  •  囚心锁ツ
    2021-02-06 04:13

    As mentioned previously, the standard way to deal with matrices in Python is to use NumPy. Here's a function that simply reads the adjacency matrix off of the adjacency list. (The implicit ordering of the nodes is made explicit by the parameter nodes.)

    import numpy
    
    def weighted_adjmatrix(adjlist, nodes):
        '''Returns a (weighted) adjacency matrix as a NumPy array.'''
        matrix = []
        for node in nodes:
            weights = {endnode:int(weight)
                       for w in adjlist.get(node, {})
                       for endnode, weight in w.items()}
            matrix.append([weights.get(endnode, 0) for endnode in nodes])
        matrix = numpy.array(matrix)
        return matrix + matrix.transpose()
    

    In this case, weighted_adjmatrix(graph, nodes=list('123456')) gives the NumPy array

    array([[ 0, 15,  0,  7, 10,  0],
           [15,  0,  9, 11,  0,  9],
           [ 0,  9,  0,  0, 12,  7],
           [ 7, 11,  0,  0,  8, 14],
           [10,  0, 12,  8,  0,  8],
           [ 0,  9,  7, 14,  8,  0]])
    

    If a regular list is desired, the method tolist() can be called.

提交回复
热议问题