我正在使用Networkx pyhton库。
我试着测试一个定义了以下功能的项目:
def _set_up_p0(self, source):
""" Set up and return the 0th probability vector. """
p_0 = [0] * self.OG.number_of_nodes()
for source_id in source:
try:
# matrix columns are in the same order as nodes in original nx
# graph, so we can get the index of the source node from the OG
source_index = self.OG.nodes().index(source_id)
p_0[source_index] = 1 / float(len(source))
except ValueError:
sys.exit("Source node {} is not in original graph. Source: {}. Exiting.".format(
source_id, source))
return np.array(p_0)上面的代码生成了一个异常:
Traceback (most recent call last):
File "run_walker.py", line 80, in <module>
main(sys.argv)
File "run_walker.py", line 76, in main
wk.run_exp(seed_list, opts.restart_prob,opts.original_graph_prob, node_list)
File "./Python_directory/Walker/walker.py", line 57, in run_exp
p_0 = self._set_up_p0(source)
File "./Python_directory/Walker/walker.py", line 118, in _set_up_p0
print(self.OG.nodes().index(source_id))
AttributeError: 'NodeView' object has no attribute 'index'事实上,以下两行代码:
print source
print(self.OG.nodes())我们得到以下错误:
['0', '1']
['1', '0', '3', '2', '4']因此,当我调用函数_set_up_p0时,我得到了上面的异常。如果你检测到了我的错误在哪里?
发布于 2018-09-03 05:47:14
这取决于您使用的networkx版本。更多信息here。
networkx 1.x
>>> G=nx.Graph([(1,2),(3,4)])
>>> G.nodes()
[1, 2, 3, 4]networkx 2.x
>>> G=nx.Graph([(1,2),(3,4)])
>>> G.nodes()
NodeView((1, 2, 3, 4))正如您在networkx2.x中看到的,您没有列表,而是一个NodeView。
您可以使用list(G.nodes())转换为列表。
https://stackoverflow.com/questions/52141158
复制相似问题