![](/img/trans.png)
[英]AttributeError: 'function' object has no attribute 'index'
[英]AttributeError: 'NodeView' object has no attribute 'index'
我正在使用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版本。 更多信息在这里 。
网络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())
转换为列表。
当您向list
询问特定元素的index
,它会从头开始执行线性搜索以找到第一个匹配元素。 太慢了 这也是容易出错的,因为只会找到第一个节点,因此会丢失相同的节点。
不用转换为list
您可以enumerate
nodes
。 这将生成一系列索引和节点。
您还可以将source
转换为set
如果尚未转换),以提高查找效率:
source = set(source)
proportion = 1 / float(len(source))
for index, node in enumerate(self.OG.nodes()):
if node in source:
p_0[index] = proportion
编辑:或者,您可以使用列表p_0
在一行中创建p_0
,因此您不需要索引,因为与节点位置存在隐式一对一的关联:
p_0 = [proportion if node in source else 0.0
for node in self.OG.nodes()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.