編集:この解決策はより明確になるはずです。これは、新しいアプローチではなく、以前のソリューション ( 1、2 ) の作り直しです。単一のループでコピーがないため、これが理解しやすくなります。
インポート コピー インポート csv インポート StringIO
csv_str = """X,,,
X,A,,
X,A,R,
X,A,R,X
X,A,R,Y
X,B,,
X,B,S,
X,B,S,X
"""
reader = csv.reader(StringIO.StringIO(csv_str))
idx = 0
data = []
for row in reader:
# insert the row id
row.insert(0, idx + 1)
# insert a dummy parent id, it will be replaced with the real
# value later
row.insert(1, -1)
# how deep is the current row
depth = len([r for r in row if r is not ''])
# insert the depth as the last value in the row
row.append(depth)
if idx > 0:
# if it's not the first row, calculate it's parent
# calculate the depth of the previous row
prev_depth = data[idx - 1][-1]
if depth > prev_depth:
# if it's deeper than the previous row, then the previous
# row is the parent row
row[1] = data[idx - 1][0]
elif depth == prev_depth:
# if it's the same depth as the previous row then it has
# the same parent as the previous row
row[1] = data[idx - 1][3]
else:
# if it's shallower than the previos row, find the
# nearest previous row with the same depth and use it's
# parent as this row's parent.
ridx = idx - 1
while (prev_depth != depth and ridx >= 0):
prev_depth = data[ridx - 1][-1]
ridx -= 1
row[1] = data[ridx - 1][0]
else:
# if it's the first row it's parent is 0
row[1] = 0
# store the new row
data.append(row)
idx += 1
# write the CSV
output = StringIO.StringIO()
writer = csv.writer(output)
for row in data:
# skip the depth value in each row
writer.writerow(row[:-1])
print output.getvalue()
ここで動作中のコードを確認できます: http://codepad.org/DvGtOw8G