I want to sort a graph object that I have read through networkx library in Python, in the increasing order of edgeweight. It seems that the sort
command of python won't apply to graph objects. I am sure there is a easy way to sort this object, but I am not sure how. Any help will be appreciated.
For example, my first three edges are
1 3 5250
1 4 74
1 5 3659
After sorting I would hope that their order is changed to
1 4 74
1 5 3659
1 3 5250
Here is my code so far
import networkx as nx
g=nx.read_weighted_edgelist(fname,nodetype=int)
I am trying to sort the object g
.
import networkx as nx
edgelist = [
(1, 3, {'weight':5250}),
(1, 4, {'weight': 74}),
(1, 5, {'weight': 3659})]
G = nx.Graph(edgelist)
for a, b, data in sorted(G.edges(data=True), key=lambda x: x[2]['weight']):
print('{a} {b} {w}'.format(a=a, b=b, w=data['weight']))
yields
1 4 74
1 5 3659
1 3 5250
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With