【问题标题】:NetworkX: How to find the source and target nodes of a directed edgeNetworkX:如何找到有向边的源节点和目标节点
【发布时间】:2016-04-12 05:26:12
【问题描述】:

同上..我在 NetworkX 文档中找不到任何内容...

在 Python Igraph 中,我可以使用:

import igraph as ig
G = ig.Graph(directed=True)
G.add_vertices(2)
G.add_edge(0,1)
eid = G.get_eid(0,1)
edge = G.es[eid]
nodes = (edge.source, edge.target)
print nodes

【问题讨论】:

  • 如果你能提供更多关于你想要什么的信息,那将更容易回答你的问题。你的出发点是什么?有向边?
  • @Joel:见上面的编辑 ;-)

标签: python graph nodes networkx edges


【解决方案1】:

元组的顺序很重要。第一个元素是源,第二个是目标。

In [1]: import networkx as nx

In [2]: G = nx.DiGraph()

In [3]: G.add_edge(1,2) # 1->2

In [4]: G.add_edge(2,3) # 2->3

In [5]: list(G.edges())
Out[5]: [(1, 2), (2, 3)] # 1->2 and 2->3

In [6]: G.add_edge(42,17) # 42->17

In [7]: list(G.edges())
Out[7]: [(1, 2), (2, 3), (42, 17)]

In [8]: for e in G.edges():
   ...:     source,target = e
   ...:     print source
   ...:     
1
2
42

【讨论】:

    【解决方案2】:

    对于networkx,边只是具有两个节点实例的元组:

    g = networkx.DiGraph()
    g.add_edge(1,2)
    edge1 = networkx.edges(g)[0]
    print type(edge1), edge1
    print "source:", edge1[0]
    print "target:", edge1[1]
    print g.neighbors(edge1[0])
    

    【讨论】:

    • @sal:那么您可能应该更具体地了解您到底想知道什么!
    • 这确实回答了这个问题。您问如何找到源边和目标边的列表
    【解决方案3】:

    虽然我来得太晚了,但我想为我的提案做出贡献,因为我一直在寻找相同的答案:

    我还在 networkx 包中寻找一个命令来查找有向图的“源”和“目标”。但是图论框架内的有向图的“源”和“目标”不仅仅是这个线程中回答的每条边的源和目标,而是相当于无向图的叶子。也就是度数为1的源节点和目标节点(当然方向不同)。

    我建议以下代码:

    import network as nx
    G = nx.DiGraph()  # initializes a directed graph
    edges = [(1,2),(2,3),(3,5),(4,5),(5,6)]
    G.add_edges_from(graph)  # adds the edges to the graph G
    sources = [x for x in G.nodes() if G.out_degree(x)==1 and G.in_degree(x)==0]
    targets = [x for x in G.nodes() if G.out_degree(x)==0 and G.in_degree(x)==1]
    

    【讨论】:

      【解决方案4】:

      只需使用 g.edges()。

      import networkx as nx
      g=nx.Graph()
      

      添加您的节点和边,以您希望的方式以及何时拥有它

      g.edges() 
      

      将返回一个包含相邻节点的元组列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多