【问题标题】:python find root/parent based on list of tuplespython根据元组列表查找根/父
【发布时间】:2016-11-10 11:48:09
【问题描述】:

假设我有一个元组列表,其中存储了一些键(字符串):

l=[
    (a,b),
    (b,c),
    (c,d),
    (d,e),
    (e,f),
    (w,x),
    (w,t),
    (t,q),
    (q,r),
    (q,u),

]

如何找到列表中元组之间的所有关系(尤其是 HEAD),例如:

a<-b<-c<-d<-e<-f
w<(-x,t-<q-<(r,u))

所以我知道fa 的大孙子?

问候 JS.

【问题讨论】:

  • 请澄清以下内容的含义:w&lt;(-x,t-&lt;q-&lt;(r,u))
  • 这些关系可以是周期性的吗?即可以a&lt;-b&lt;-c&lt;-a
  • 不,不是周期性的。 w 是 x 和 t 的父级。 t 是 q 的父级。 q 是 r 和 u 的父级。

标签: python list relationship


【解决方案1】:

我们将有一个字典映射名称到Nodes,然后将这些节点构建成树。

from collections import defaultdict
class Node:
    def __init__(self):
        children = []
    def add_child(self, child):
        self.children.append(child)
    def ancestor_of(self, descendant):
        if self == descendant:
            return [self]
        for child in children:
            c=child.ancestor_of(descendant)
            if c:
                return [self, *c]
        return None

node_dict = defaultdict(Node)
for fst, snd in l: #assuming a and b are strings
    d[fst].add_child(d[snd])
#Query trees using ancestor_of

【讨论】:

    【解决方案2】:

    这个怎么样,


    源码如下。

    import networkx as nx
    import matplotlib.pyplot as plt
    from networkx.drawing.nx_agraph import graphviz_layout
    
    G = nx.DiGraph()
    
    l=[
        ('a','b'),
        ('b','c'),
        ('c','d'),
        ('d','e'),
        ('e','f'),
        ('w','x'),
        ('w','t'),
        ('t','q'),
        ('q','r'),
        ('q','u')
        ]
    
    for t in l:
        G.add_edge(t[0], t[1])
    
    pos=graphviz_layout(G, prog='dot')
    nx.draw(G, pos, with_labels=True)   
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      相关资源
      最近更新 更多