网络错误: 当节点有标签时,networx.descendants() 函数出错

2024-06-16 10:10:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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'}

我做错什么了吗?在


Tags: fromnetworkxaddnode节点错误nownodes
2条回答

如果您检查哪个节点比较近:

for node in nodes :
    print(node, type(G[node]), G[node].keys())

您将获得:

^{pr2}$

您可以看到,G[node]是一个字典,其键对应于它共享边的其他节点。您将绕过其常规的节点创建例程,并在mix中插入一个名为occurrences的节点,通过edge连接到其他节点。我之所以说trying to是因为这个节点没有正确设置,并且在以这种方式添加时无法正常工作。在

如果要在节点上存储其他属性,可以设置节点类,例如:

class Node(object):
    def __init__(self, letter):
        self.letter = letter

    def __str__(self):
        return self.letter

…然后:

nodes = [Node(l) for l in ["A", "B", "C", "D", "E"]]

现在可以将任何您喜欢的属性附加到这些节点(但不能附加到G[node])。在

@Gerrat使用自定义节点类的方法将起作用。但是推荐的方法是使用G.node来存储节点数据。你说得差不多了。这是故障代码

for node in nodes :
    G[node]['occurrences'] = 1 # INCORRECT, corrupts data structure

for node in nodes :
    G.node[node]['occurrences'] = 1 # CORRECT

工作实例

^{pr2}$

关于如何设置graph、node和edge属性,https://networkx.readthedocs.org/en/stable/tutorial/tutorial.html#adding-attributes-to-graphs-nodes-and-edges有更多信息。在

相关问题 更多 >