Networkx 邻居集不打印 [英] Networkx neighbor set not printing
问题描述
我的 networkx 代码有点问题.我试图从图中的一个节点中找到所有邻居,但是....
I have a little problem with my networkx code. I am trying to find all the neighbors from a node in a graph, but....
neighbor = Graph.neighbors(element)
print(neighbor)
输出:
<dict_keyiterator object at 0x00764BA0>
而不是我应该得到的所有邻居......我的一个使用旧版本 networkx 的朋友没有收到此错误,他的代码完全相同并且运行良好.
谁能帮我?降级我的 networkx 不是一种选择.
Instead of all the neighbors I am supposed to get... A friend of mine, who is using an older version of networkx does not get this error, his code is exactly the same and works perfectly.
Can anyone help me? Downgrading my networkx is not an option.
这是我的完整代码
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
推荐答案
从 networkx 2.0 开始,Graph.neighbors(element)
返回迭代器而不是列表.
From networkx 2.0 onwards, Graph.neighbors(element)
returns an iterator rather than a list.
要获取列表,只需应用 list
To get the list, simply apply list
list(Graph.neighbors(element))
或使用列表推导式:
neighbors = [n for n in Graph.neighbors(element)]
第一种方法(首先由 Joel 提及)是推荐的方法,因为它更快.
The first method (first mentioned by Joel) is the recommended method, as it's faster.
这篇关于Networkx 邻居集不打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!