Networkx neighbor set not printing

匆匆过客 提交于 2019-12-04 05:46:46

From networkx 2.0 onwards, Graph.neighbors(element) returns an iterator rather than a list.

To get the list, simply apply list

list(Graph.neighbors(element))

or use list comprehension:

neighbors = [n for n in Graph.neighbors(element)]

The first method (first mentioned by Joel) is the recommended method, as it's faster.

Reference: https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.neighbors.html

As others have noted, in networkx 2.0 neighbors returns an iterator rather than a list. Networkx has provided a guide for migrating code written in 1.x to 2.0. For neighbors, it recommends

list(G.neighbors(n))

(see Fastest way to convert an iterator to a list). The migration guide provides the example:

>>> G = nx.complete_graph(5)
>>> n = 1
>>> G.neighbors(n)
<dictionary-keyiterator object at ...>
>>> list(G.neighbors(n))
[0, 2, 3, 4]

You can make method for that like,

def neighbors(G, n):
"""Return a list of nodes connected to node n. """
return list(G.neighbors(n))

And call that method as:

print(" neighbours = ", neighbors(graph,'5'))

Where 5 is the node in a graph and

graph = nx.read_edgelist(path, data = (('weight', float), ))

and path variable contains dataset file path value where data is in more numbers of nodes and edges.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!