gpt4 book ai didi

python - 属性错误: 'NodeView' object has no attribute 'index'

转载 作者:行者123 更新时间:2023-12-02 03:29:56 24 4
gpt4 key购买 nike

我正在使用 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 时,我得到了上述异常。如果您发现了我的错误在哪里,请

最佳答案

这取决于您使用的networkx版本。更多信息here .

网络x 1.x

>>> G=nx.Graph([(1,2),(3,4)])
>>> G.nodes()
[1, 2, 3, 4]

网络x 2.x

>>> G=nx.Graph([(1,2),(3,4)])
>>> G.nodes()
NodeView((1, 2, 3, 4))

正如您在 networkx2.x 中看到的,您没有列表,只有 NodeView。
您可以使用 list(G.nodes()) 转换为列表。

关于python - 属性错误: 'NodeView' object has no attribute 'index' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52141158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com