【问题标题】:Faster way to build a tree graph using Networkx Python?使用 Networkx Python 构建树形图的更快方法?
【发布时间】:2015-01-09 20:38:15
【问题描述】:

有没有更快、更好的方法来构建 Networkx 树。目前,我的代码是

for numb in range(0,len(previous)):
    nodos = list(chunks(current,3))
        for i in range(0,3):
            G.add_edge(previous[numb],nodos[numb][i])

这通过以下方式起作用: 1. 树有 3 个分支(或边缘)。我有两个数组:

previous = [x,y,z] #These nodes have already been added to the graph
current = [xx,xy,xz, xy,yy,yz, xz,yz,zz] #This nodes need to be added.

理想情况下,我应该执行以下操作:

1. Start with x in previous:
1.1 Pick the first 3 nodes in current (i.e. xx,xy,xz)
1.1.1 Add the nodes-edges: x->xx, x->xy, x->xz

到目前为止,我的代码是这样的:

1. Start with x in previous
2. Partition current into chunks of 3 items: [[xx,xy,xz], [xy,yy,yz], [xz,yz,zz]]
3. Loop through all the nodes in these chunks:
4. Add x->xx, loop again, add x->xy... etc.

我的实现效率极低。你将如何有效地做到这一点?谢谢

【问题讨论】:

    标签: python numpy networkx


    【解决方案1】:

    你可以使用https://github.com/networkx/networkx/blob/master/networkx/generators/classic.py#L50的辅助函数

    def _tree_edges(n,r):
        # helper function for trees
        # yields edges in rooted tree at 0 with n nodes and branching ratio r
        nodes=iter(range(n))
        parents=[next(nodes)] # stack of max length r
        while parents:
            source=parents.pop(0)
            for i in range(r):
                try:
                    target=next(nodes)
                    parents.append(target)
                    yield source,target
                except StopIteration:
                    break
    
    print list(_tree_edges(13,3))
    #[(0, 1), (0, 2), (0, 3), (1, 4), (1, 5), (1, 6), (2, 7), (2, 8), (2, 9), (3, 10), (3, 11), (3, 12)]
    import networkx as nx
    G = nx.Graph(_tree_edges(13,3))
    

    如果您想要整数以外的节点,您可以像这样重新标记或在输入中指定它们

    def _tree_edges(nodes,r):
        # helper function for trees
        # yields edges in rooted tree with given nodes and branching ratio r
        nodes=iter(nodes)
        parents=[next(nodes)] # stack of max length r
        while parents:
            source=parents.pop(0)
            for i in range(r):
                try:
                    target=next(nodes)
                    parents.append(target)
                    yield source,target
                except StopIteration:
                    break
    
    nodes = list('abcdefghijklm')
    print list(_tree_edges(nodes,3))
    

    【讨论】:

    • 谢谢!我不知道这存在。但是我仍然有一个问题,如果 n,r 是数字,这很好用,但在我的情况下它们是字母。所以 [(x,xx),(x,xy),(x,xz),(y,xy) .. 等等]。但是如果 r 不是数字,我就不能使用这个函数。关于如何解决这个问题的任何想法?
    猜你喜欢
    • 2018-07-01
    • 2021-05-14
    • 2015-11-28
    • 2016-09-14
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2019-11-18
    • 2019-02-28
    相关资源
    最近更新 更多