How can I make a list of edge weights in python's NetworkX module

605 views Asked by At

I am having trouble with NetworkX and could use some help.

I have never used this module before this current program and after searching extensively I cannot seem to find a solution that fits.

I am currently trying to create a list of edge weights to be used in a nearest neighbor function which will be used in other functions for path finding purposes.

I currently have this code

    def getNearestNeighbor(self, node):
        edge_list = []
        weight_list = []
        node_list = [nx.all_neighbors(self.G, node)]
        edge_list = [nx.edges(self.G, node)]
        f = node
        for i, f, data in self.G.edges(data=True):
            weight_list.append(data['weight'])

Unfortunately, this returns the weight of every edge in the graph, but I only want those related to a targeted node. How would I go about this?

When I run this through my sorting algorithm it returns an Index_Error because the weight list has indices which go out of the range of the edge_list.

1

There are 1 answers

0
Zach Angemi On

Original:

    def getNearestNeighbor(self, node):
        edge_list = []
        weight_list = []
        node_list = [nx.all_neighbors(self.G, node)]
        edge_list = [nx.edges(self.G, node)]
        f = node
        for i, f, data in self.G.edges(data=True):
            weight_list.append(data['weight'])

New:

    def getNearestNeighbor(self, node):
        edge_list = []
        weight_list = []
        node_list = list(nx.all_neighbors(self.G, node))
        edge_list = list(nx.edges(self.G, node))
        f = node
        for i, f, data in self.G.edges(node, data = 'weight'):
            weight_list.append(data)

The problem was actually the edge list. Because the edges function returns a tuple, edge_list only had one index, the tuple.