针对一个包含父子关系的表格(csv格式),我正在尝试使用表格中的所有数据获取可能的父子关系组合链。我碰到的问题是,如果存在多个次级父母(参见第3和第4行),第二个次级父母组合(第4行)不会被包括在迭代中。
数据示例:
child,parent
A,B
A,C
B,D
B,C
C,D
预期的链结果:
D|B|A
D|C|B|A
D|C|A
实际的链结果:
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
D|C|B|A
作为预期结果。如果排除第四行 B|C 组合,我认为这个结果不会出现。 - Gerrat