我正在使用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时,出现上述异常。如果您检测到我的错误在哪里
答案 0 :(得分:2)
这取决于您使用的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())
转换为列表。
答案 1 :(得分:1)
当您向list
询问特定元素的index
时,它会从头开始执行线性搜索以找到第一个匹配元素。太慢了这也是容易出错的,因为只会找到第一个节点,因此会丢失相同的节点。
您可以enumerate
list
而不是转换为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
edit:或者,您可以使用列表推导功能在一行中创建p_0 = [proportion if node in source else 0.0
for node in self.OG.nodes()]
,因此不需要索引,因为与节点位置存在隐式一对一的关联:
#include <stdio.h>
int main() {
// declaration of variables
int total_height;
int hundred_feet_rope;
int ten_feet_rope;
//prompt user for input information
printf("How tall is the mountain?\n");
scanf("%d", &total_height);
//calculations for how many skeins of 100 feet rope are needed, and how many 10 feet rope is needed
hundred_feet_rope = total_height / 100;
ten_feet_rope = total_height % 100 / 10;
//output results
printf("You will need %d skeins of 100 feet rope and %d skeins of 10 feet rope!\n", hundred_feet_rope, ten_feet_rope);
return 0;
}