【发布时间】:2015-01-31 08:54:07
【问题描述】:
对于子-父关系表 (csv),我正在尝试使用表中的所有数据收集可能的父子关系组合链。我正在尝试解决一个问题,即如果存在多个子父项(参见第 3 行和第 4 行),则迭代中不包含第二个子父项组合(第 4 行)。
数据示例:
孩子,父母
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
【问题讨论】:
-
我不明白这一点:
I am trying against a problem where if multiple sub-parents exist (see rows 3 & 4), the second sub-parent combination (row 4) is not included in the iteration- 但您按预期列出了D|C|B|A。如果排除第 4 行:B|C 对,我认为不会出现这样的结果。 -
当前代码不考虑第 4 行。这正是问题所在。
-
作为旁白的莎拉,看着你的个人资料,你问了很多问题,人们已经回答了。如果有人提供了您认为可以接受的答案,您应该点击他们答案旁边的复选标记
accept。到目前为止,您还没有接受任何内容。
标签: python for-loop iteration hierarchy