编辑:这个解决方案应该更清楚。这是对先前解决方案(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