How can I reference the attributes of an edge in a loop?

31 views
Skip to first unread message

Zach Angemi

unread,
Apr 29, 2022, 12:56:21 PMApr 29
to networkx-discuss
Hello, simple question here, but I am brand new to NetworkX. I'm trying to run a Nearest Neighbor Heuristic between points, and to do so I am trying to sort a list of edges to neighbors of a node by the weight of the edges. To get the weights sorted I need to add the weight attribute value of the edges to a list that I can then sort.

How would I go about getting the weights from the edges, or am I going about this all wrong? 

Thanks!

Dan Schult

unread,
Apr 29, 2022, 4:25:23 PMApr 29
to networkx...@googlegroups.com
The edges are reported with `G.edges`, and you can ask for edges involving a node n using `G.edges(n)` and that has an optional keyword argument to get the weight: `G.edges(n, data="weight")` as a container of edge tuples: `(n, nbr, wt)`. Then you can sort the result based on the last entry in the edge tuple:

sorted(G.edges(n, data="weight", default=1), key=lambda e:e[-1])


More info similar to this is available in the main documentation tutorial.
Reply all
Reply to author
Forward
0 new messages