Question

I want to compare nodes of different edges in the graph. How can I get the nodes(n1 and n2) from the edge(n1,n2)?

Was it helpful?

Solution

An edge in NetworkX is defined by its nodes, so I'm not really sure what you're asking here. A specific edge in the graph is just a tuple of nodes, with an optional weighting.

import networkx as nx
g = nx.Graph()
g.add_edge(1,2)
g.add_edge(2,3)
g.edges()

gives

[(1, 2), (2, 3)]

As you can see, the list of edges explicitly provides the nodes of each edge.

Update: Does this do what you want?

#!/usr/bin/python

import networkx as nx
import random

g = nx.Graph()
g.add_edges_from([(1,2),(2,3),(1,4),(2,5)])

random_edge = random.choice(g.edges())

print 'Randomly selected edge is:', random_edge
print 'Nodes are', random_edge[0], 'and', random_edge[1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top