我有一个深度嵌套子项的数据库模型.我试图添加所有底层ID(所有级别)添加到字典条目.我目前的代码如下:
children = obj.children
for child in children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
Run Code Online (Sandbox Code Playgroud)
这段代码功能齐全,但问题相当明显.我不想一遍又一遍地编写相同的代码:它很丑陋,不切实际且不易维护.我该怎么做?
一个循环怎么样?
children = list(obj.children)
while children:
child = children.pop()
data["children_ids"].append(child.id)
grandchildren = getattr(child, 'children', None)
if grandchildren:
children.extend(list(grandchildren))
Run Code Online (Sandbox Code Playgroud)
使用递归函数在不同的子代上运行相同的代码:
def add_children_ids(ids, children):
for child in children:
ids.append(child.id)
add_children_ids(ids, child.children)
children = obj.children
data['children_ids'] = []
add_children_ids(data['children_ids'], children)
Run Code Online (Sandbox Code Playgroud)
由于ids是一个可变的列表,没有必要到return它
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |