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)?
A:
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]
ire_and_curses
2010-05-01 14:52:25
suppose I have an edge list, one of them might be edge(2,3) which is the edge between node 2 and 3. I want the program, randomly give me an edge from my data, and also give me it's nodes, like here gives me 2 and 3.
masti
2010-05-01 16:01:45
@masti: I've updated my answer. Is this what you mean?
ire_and_curses
2010-05-01 16:45:44
yes, thanks. Actually this is first part of my program, I need to work with these nodes later on. So I was thinking there might be a function to get_nodes, the reverse of the function get_edge... But it is still good enough!
masti
2010-05-01 17:09:09