Networkx邻居设置为不打印

问题描述 投票:6回答:3

我有我的networkx代码有点问题。我试图找到所有从一个图形中的节点邻居,但是....

neighbor = Graph.neighbors(element)
print(neighbor)

输出:

<dict_keyiterator object at 0x00764BA0>

相反,我应该得到所有邻国...我的一个朋友,谁在使用networkx的旧版本并没有得到这个错误的,他的代码是完全一样的和完美的作品。 谁能帮我?降级我networkx是不是一种选择。

Edit:

这是我的完整代码

Graph = nx.read_graphml('macbethcorrected.graphml')    
actors = nx.nodes(Graph)

for actor in actors:
    degree = Graph.degree(actor)
    neighbor = Graph.neighbors(actor)
    print("{}, {}, {}".format(actor, neighbor, degree))

这是我使用的图形:http://politicalmashup.nl/new/uploads/2013/09/macbethcorrected.graphml

python-3.x graph nodes networkx
3个回答
9
投票

从networkx 2.0起,Graph.neighbors(element)返回一个迭代器,而不是一个列表。

要获取列表,简单地套用list

list(Graph.neighbors(element))

或使用列表理解:

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

第一种方法(第一通过Joel提及)是推荐的方法,因为它的速度更快。

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


1
投票

正如其他人指出,在networkx 2.0 neighbors返回一个迭代器,而不是一个列表。 Networkx提供写入的1.x〜2.0 guide for migrating code。对于neighbors,它建议

list(G.neighbors(n))

(见Fastest way to convert an iterator to a list)。迁移指南提供的例子中:

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

0
投票

您可以为喜欢的方法,

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

并调用该方法为:

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

其中图5是曲线图的节点和

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

和路径变量包含数据集的文件路径值,其中数据是在节点和边的多个数字。

© www.soinside.com 2019 - 2024. All rights reserved.