简体   繁体   中英

How to access the first neighbor of a node in NetworkX?

I created a graph of TestClass objects in NetworkX. I have two TestClass objects obj1 and obj2 and I want to connect their first neighbors.

Code

first_node = [node for node in G.nodes() if node==obj1][0]
second_node = [node for node in G.nodes() if node==obj2][0]                
G.add_edge(first_node.neighbours[0], second_node.neighbours[0])

I get an error message that TestClass object has no attribute neighbors .

How do you access these two objects as nodes in the Graph to work with their neighboring nodes?

Neighbors are accessed using the method Graph.neighbors(n) , where n is a node.

Since G.neighbors returns an iterator over the neighboring nodes, to use a list accessor, you would first need to wrap the iterator in a list initializer.

G.add_edge(list(G.neighbors(first_node))[0], list(G.neighbors(second_node))[0])

A cleaner way would be to call next() on the iterators, which avoids creating new list objects and eliminates the index accessors.

G.add_edge(next(G.neighbors(first_node)), next(G.neighbors(second_node)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM