Python中的递归循环功能 [英] Recursive looping function in Python
问题描述
我有一个数据库,该数据库对与n
嵌套级别的文件夹关系进行建模.对于任何给定的文件夹,我想生成所有子文件夹的列表.
I have a database that models a foldering relationship to n
levels of nesting. For any given folder, I want to generate a list of all child folders.
假设我有一个名为getChildFolders()
的函数,调用这种递归循环的最有效方法是什么?
Assuming I have a function called getChildFolders()
, what is the most efficient way to call this kind of recursive loop?
以下代码可用于4个层次的嵌套,但是我希望在指定递归深度或在没有更多后续子代时智能地停止循环方面具有更大的灵活性.
The following code works for 4 levels of nesting, but I'd like more flexibility in either specifying the depth of recursion, or in intelligently stopping the loop when there are no more children to follow.
folder_ids = []
folder_ids.append(folder.id)
for entry in child_folders:
folder_ids.append(entry.id)
child_folders_1 = getChildFolders(entry.id)
for entry_1 in child_folders_1:
folder_ids.append(entry_1.id)
child_folders_2 = getChildFolders(entry_1.id)
for entry_2 in child_folders_2:
folder_ids.append(entry_2.id)
child_folders_3 = getChildFolders(entry_2.id)
for entry_3 in child_folders_3:
folder_ids.append(entry_3.id)
推荐答案
递归函数是实现此目的的一种好方法:
A recursive function is a nice way to do this:
def collect_folders(start, depth=-1)
""" negative depths means unlimited recursion """
folder_ids = []
# recursive function that collects all the ids in `acc`
def recurse(current, depth):
folder_ids.append(current.id)
if depth != 0:
for folder in getChildFolders(current.id):
# recursive call for each subfolder
recurse(folder, depth-1)
recurse(start, depth) # starts the recursion
return folder_ids
这篇关于Python中的递归循环功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!