Python:父子层次结构的组合

2024-06-26 13:27:37 发布

您现在位置:Python中文网/ 问答频道 /正文

对于子-父关系表(csv),我尝试使用表中的所有数据收集可能的父子关系组合链。我试图解决这样一个问题:如果存在多个子父级(参见第3行和第4行),则第二个子父级组合(第4行)不包含在迭代中。在

数据示例:

子女,父母

A,B
A,C
B,D
B,C
C,D

预期链结果:

^{pr2}$

实际链结果:

D|B|A
D|C|A

编码

find= 'A' #The child for which the code should find all possible parent relationships
sequence = ''
with open('testing.csv','r') as f:     #testing.csv = child,parent table (above example)
    for row in f:
        if row.strip().startswith(find):
            parent = row.strip().split(',')[1]
            sequence = parent + '|' + find
            f1 = open('testing.csv','r')
            for row in f1:
                if row.strip().startswith(parent):
                    parent2 = row.strip().split(',')[1]
                    sequence = parent2 + '|' + sequence
                    parent = parent2
        else:
            continue
        print sequence

Tags: csv数据inchildforifopenfind
2条回答

你看过那篇精彩的文章了吗?真正理解python中的模式是必不可少的。您的问题可以看作是一个图问题-查找关系基本上就是查找从子节点到父节点的所有路径。在

由于可能存在任意数量的嵌套(child->;parent1->;parent2…),因此需要递归解决方案来查找所有路径。在您的代码中,有2个for循环,这最多只会产生3级路径。在

下面的代码是根据上面的链接修改的,以解决您的问题。函数find_all_paths需要一个图形作为输入。在

让我们从文件创建图形:

graph = {} # Graph is a dictionary to hold our child-parent relationships.
with open('testing.csv','r') as f:
    for row in f:
        child, parent = row.split(',')
        graph.setdefault(parent, []).append(child)

print graph

对于您的样本,应该打印:

^{pr2}$

以下代码直接取自本文:

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]

    if not graph.has_key(start):
        return []

    paths = []

    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
            for newpath in newpaths:
                paths.append(newpath)
    return paths

for path in find_all_paths(graph, 'D', 'A'):
    print '|'.join(path)

输出:

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

我不确定这是否是最有效的方法(但是在每一行再次读入文件会更糟)。在

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)

结果:

^{pr2}$

相关问题 更多 >