开发者

How do I get nodes from the specific edge in the networkx?

开发者 https://www.devze.com 2022-12-29 00:45 出处:网络
I want to compare nodes of different edges in the 开发者_如何学JAVAgraph. How can I get the nodes(n1 and n2) from the edge(n1,n2)?An edge in NetworkX is defined by its nodes, so I\'m not really sure w

I want to compare nodes of different edges in the 开发者_如何学JAVAgraph. How can I get the nodes(n1 and n2) from the edge(n1,n2)?


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]


The answer to what I think was the intended question is:

graph = networkx.read_graphml('some_fully_loaded_graph.graphml')
edge0 = list(graph.edges(data=True))[0]

subgraph = graph.edge_subgraph([edge0[:2]])
nodes0 = list(subgraph.nodes(data=True))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号