Reputation: 1181
Is there a better way to obtain the list of nodes that connect to a given one in a directed graph via a single edge (whether inbound or outbound)?
Here is what I came up with. First I build and draw a demo DiGraph:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([
('A','B'),
('B','C'),
('C','D'),
('D','E'),
('F','B'),
('B','G'),
('B','D'),
])
nx.draw(
G,
pos=nx.nx_agraph.graphviz_layout(G, prog='dot'),
node_color='#FF0000',
with_labels=True
)
and now I'd like to get all "neighbouring nodes for node 'B'" and currently I do so with:
node= 'B'
incoming = [n for n in G.predecessors(node)]
outgoing = [n for n in G.successors(node)]
neighbours = incoming + outgoing
print(neighbours)
['A', 'F', 'C', 'G', 'D']
Is there a simpler, better, faster way of achieving this result?
Upvotes: 1
Views: 788
Reputation: 26686
I would use networkx inbuilt methods instead
from networkx import*
list(all_neighbors(G, 'B'))
['A', 'C', 'G', 'D', 'F']
Upvotes: 4
Reputation: 787
From the documentation of the class nx.DiGraph
the edges reporting object is often more convenient:
>>> for u, v, weight in G.edges(data="weight"):
... if weight is not None:
... # Do something useful with the edges
... pass
What you want can be achieved using G.edges
and a list comprehension like this
[
other_node
for edge in G.edges()
for other_node in edge
if node in edge and other_node != node
]
Upvotes: 1