【问题标题】:How to access attributes of a class instance which is a graph node via the graph?如何通过图访问作为图节点的类实例的属性?
【发布时间】:2020-07-24 03:13:31
【问题描述】:

类定义:

class Blah:
    def __init__(self,x):
        self.x = x

main() 的一部分:(导入的 networkx)

G = networkx.Graph()
H = []

for i in range(1,5):
    H.append(Blah(i))

for i in H:
    G.add_node(i)

现在,如果我想使用 G 打印 H[2].x,我该怎么做?

G[2].x 肯定行不通。 G(H[2]).x 会起作用吗?

只是询问信息。我可以在我的问题中使用 H。

【问题讨论】:

  • 我想你的意思是for i in H: G.add_node(i)
  • @yatu 哦,对不起,那是一个打字错误。已编辑。
  • 那么你期待的是什么?
  • 他是节点数据吗?
  • @yatu 我想访问 G 的特定节点的 x,但我不知道该特定节点是 H 的哪个元素。有没有办法通过 G 访问 x?

标签: python nodes networkx undirected-graph


【解决方案1】:

所以如果你定义:

class Blah:
    def __init__(self,x):
        self.x = x

G = networkx.Graph()
H = []

for i in range(1,5):
    H.append(Blah(i))

for i in H:
    G.add_node(i)

现在你想访问 G 的节点的属性。为此,你需要使用 networkx 命令访问 G 的节点:

for node in G:
    print(node.x)
> 1
> 2
> 3
> 4

【讨论】:

  • 感谢@Joel 的回答。有没有办法索引节点(如 G[2])?
【解决方案2】:

可以访问节点数据如下图

print(list(G.nodes())[1].x)

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2012-03-11
    • 2013-06-07
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多