Python: Combinations of parent-child hierarchy

前端 未结 2 560
不知归路
不知归路 2021-01-06 19:25

For a child-parent relationship table (csv), I am trying to gather possible parent to child relationship combination chains using all data in the table. I am trying against

2条回答
  •  清酒与你
    2021-01-06 19:37

    I'm not sure if this is the most efficient way to do it (but reading the file in again on every row would be worse).

    find= 'A' #The child for which the code should find all possible parent relationships
    sequences = set(find)
    
    # we'll build up a chain for every relationship, then strip out un-needed ones later
    with open('testing.csv','r') as f:     #testing.csv = child,parent table (above example)
        for row in f:
            child, parent = row.strip().split(',')
            sequences.add(parent + '|' + child)
            for c in sequences.copy():  
                if c[0] == child:
                    sequences.add(parent + '|' + c)
    
    
    # remove any that don't end with our child:
    sequences = set(s for s in sequences if s.endswith(find))
    
    # get all shorter chains when we have a longer one
    extra = set()
    for g1 in sequences:
        for g2 in sequences:
            if g2[2:] == g1:
                extra.add(g1)
    
    # remove the shorter chains
    sequences.difference_update(extra)
    
    for chain in sequences:
        print(chain)
    

    Results:

    D|C|A
    D|C|B|A
    D|B|A
    

提交回复
热议问题