我在python3.4中使用networkx,当我试图找到可访问的节点时,我得到了一个奇怪的错误。我认为这与我之前设置的节点的可选属性有关。此最小代码会复制错误:
import networkx as nx
G = nx.Graph()
nodes = ["A", "B", "C", "D", "E"]
G.add_nodes_from(nodes)
G.add_edge("A", "B")
G.add_edge("A", "C")
G.add_edge("A", "D")
G.add_edge("B", "E")
for node in nodes :
G[node]['occurrences'] = 1
print("Now computing nodes reachable from \"A\"...")
reachableNodes = nx.descendants(G, "A")
print("List of reachable nodes:", reachableNodes)
输出为:
^{pr2}$现在,如果我在设置标记“occurrences”时注释这些行,就会得到预期的结果:
Now computing nodes reachable from "A"...
List of reachable nodes: {'B', 'D', 'C', 'E'}
我做错什么了吗?在
如果您检查哪个节点比较近:
您将获得:
^{pr2}$您可以看到,
G[node]
是一个字典,其键对应于它共享边的其他节点。您将绕过其常规的节点创建例程,并在mix中插入一个名为occurrences
的节点,通过edge连接到其他节点。我之所以说trying to
是因为这个节点没有正确设置,并且在以这种方式添加时无法正常工作。在如果要在节点上存储其他属性,可以设置节点类,例如:
…然后:
现在可以将任何您喜欢的属性附加到这些节点(但不能附加到
G[node]
)。在@Gerrat使用自定义节点类的方法将起作用。但是推荐的方法是使用
G.node
来存储节点数据。你说得差不多了。这是故障代码工作实例
^{pr2}$关于如何设置graph、node和edge属性,https://networkx.readthedocs.org/en/stable/tutorial/tutorial.html#adding-attributes-to-graphs-nodes-and-edges有更多信息。在
相关问题 更多 >
编程相关推荐