我想正确更新我的父母编号。
我现有的字典清单
id prj_id parent
1 808348 1
2 808352 2
3 808356 3
4 808361 4
5 808365 0
6 808370 0
7 808370 6
8 808370 7
9 808370 8
现在我想得到它,我的父母得到了父项目的编号
我的代码:
index = 0
last_prj_id = ""
for row in result_gantt:
current_prj_id = row['prj_id']
parent = row['parent']
parent = index
if current_prj_id == last_prj_id:
parent = last_id
else:
parent = index
last_prj_id = row['prj_id']
last_id = row['id']
代码的结果:
id prj_id parent
1 808348 0
2 808352 0
3 808356 0
4 808361 0
5 808365 0
6 808370 0
7 808370 6
8 808370 7
9 808370 8
不幸的是,我不知道我如何知道ID为7到ID 9的条目为ID为6的父级
这就是问题的外观。
id prj_id parent
1 808348 0
2 808352 0
3 808356 0
4 808361 0
5 808365 0
6 808370 0
7 808370 6
8 808370 6
9 808370 6
我不知道如何继续。感谢您的帮助
最佳答案
试试下面的代码:
result_gantt = [{"id":1,"prj_id":808348,"parent":1},{"id":2,"prj_id":808352,"parent":2},{"id":3,"prj_id":808356,"parent":3},{"id":4,"prj_id":808361,"parent":4},{"id":5,"prj_id":808365,"parent":0},{"id":6,"prj_id":808370,"parent":0},{"id":7,"prj_id":808370,"parent":6},{"id":8,"prj_id":808370,"parent":7},{"id":9,"prj_id":808370,"parent":8}]
index = 0
prev_index = 0 # To maintain the index in case of consecutive id's
last_prj_id = ""
check = False # Check for consecutive id's
for row in result_gantt:
current_prj_id = row['prj_id']
parent = row['parent']
parent = index
if current_prj_id == last_prj_id:
if not check: # Will be true in case of consecutive id's
prev_index = last_id
parent = last_id
check = True
else:
check = False
parent = index
last_prj_id = row['prj_id']
last_id = row['id']
row['parent'] = parent if not check else prev_index
for i in result_gantt:
print i
输出:
{'prj_id': 808348, 'id': 1, 'parent': 0}
{'prj_id': 808352, 'id': 2, 'parent': 0}
{'prj_id': 808356, 'id': 3, 'parent': 0}
{'prj_id': 808361, 'id': 4, 'parent': 0}
{'prj_id': 808365, 'id': 5, 'parent': 0}
{'prj_id': 808370, 'id': 6, 'parent': 0}
{'prj_id': 808370, 'id': 7, 'parent': 6}
{'prj_id': 808370, 'id': 8, 'parent': 6}
{'prj_id': 808370, 'id': 9, 'parent': 6}
关于python - Python:在for循环中更新父项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54970302/