【问题标题】:Python networkx iterating through list of subgraphsPython networkx 遍历子图列表
【发布时间】:2017-05-04 15:15:57
【问题描述】:

我在通过大型 nx 图 G 的所有可能子图获得迭代时遇到了一些麻烦,该图 G 被作为文本文件的输入。

以下是我在 StackOverflow 上找到的一些代码,但没有产生我正在寻找的代码:

    g = read_graph(sys.argv[1])

    print ('Number of subgraphs:', len(g.subgraph(g.nodes())))

    # extract subgraphs
    sub_graphs = nx.connected_component_subgraphs(g)

    for i, sg in enumerate(sub_graphs):
        print "subgraph {} has {} nodes".format(i, sg.number_of_nodes())
        print "\tNodes:", sg.nodes(data=True)
        print "\tEdges:", sg.edges() 

打印出来:

('Number of subgraphs:', 4039)
subgraph 0 has 4039 nodes
    Nodes: <generator object nodes at 0x10ed77910>
    Edges: <generator object edges at 0x10ed77910>

我想要做的是能够遍历所有可能的长度为 3 或更大的子图,然后将它们作为图执行某些功能。

谢谢!

【问题讨论】:

  • 您能否提供一个链接到您获得该代码的位置?它似乎来自以前的版本。
  • 还请澄清“长度为 3 的子图”的含义。我能想到你所说的几件事。
  • 在 networkx 的旧版本中,sg.nodes()sg.edges() 会生成节点和边列表,但现在它们会返回更高效的节点和边生成器。

标签: python iteration networkx subgraph


【解决方案1】:

我写这篇文章是假设“长度 3”意味着“至少 3 个节点”。

import networkx as nx
g = read_graph(sys.argv[1])

for subgraph in nx.connected_component_subgraphs(g):
    if subgraph.number_of_nodes()>2:
         #your code here

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多