我有一个数据库,用于建模与n
嵌套级别的文件夹关系。对于任何给定的文件夹,我想生成所有子文件夹的列表。
假设我有一个名为getChildFolders()
的函数,那么调用这种递归循环的最有效方法是什么?
以下代码适用于4个嵌套级别,但我希望在指定递归深度方面更灵活,或者在没有更多子级要遵循的情况下智能地停止循环。
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)
答案 0 :(得分:3)
递归函数是一种很好的方法:
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
答案 1 :(得分:3)
我通常避免像python中的瘟疫一样递归,因为它很慢并且因为整个堆栈溢出错误的事情。
def collect_folders(start):
stack = [start.id]
folder_ids = []
while stack:
cur_id = stack.pop()
folder_ids.append(cur_id)
stack.extend(folder.id for folder in getChildFolders(cur_id))
return folder_ids
这假定getChildFolders
在没有子节点时返回空列表。如果它做了其他事情,比如返回一个标记值或引发异常,则必须进行修改。
答案 2 :(得分:2)
def my_recursive_function(x, y, depth=0, MAX_DEPTH=20):
if depth > MAX_DEPTH:
return exhausted()
elif something(x):
my_recursive_function(frob(x), frob(y), depth + 1)
elif query(y):
my_recursive_function(mangle(x), munge(y), depth + 1)
else:
process(x, y)
# A normal call looks like this.
my_recursive_function(a, b)
# If you're in a hurry,
my_recursive_function(a, b, MAX_DEPTH=5)
# Or have a lot of time,
my_recursive_function(a, b, MAX_DEPTH=1e9)
答案 3 :(得分:0)
这是最接近你的代码,非常unpythonic:
def recurse(folder_ids, count):
folder_ids.append(folder.id)
for entry in child_folders:
folder_ids.append(entry.id)
child_folders_1 = getChildFolders(entry.id)
if count > 0:
recurse(folder_ids, count-1)
folder_ids = []
recurse(folder_ids, 4)
您应该寻找os.walk
,并采用类似的方法迭代地遍历树。
答案 4 :(得分:0)
我需要类似的东西来检查一个分层树。你可以尝试:
def get_children_folders(self,mother_folder):
'''
For a given mother folder, returns all children, grand children
(and so on) folders of this mother folder.
'''
folders_list=[]
folders_list.append(mother_folder)
for folder in folders_list:
if folder not in folders_list: folders_list.append(folder)
new_children = getChildFolders(folder.id)
for child in new_children:
if child not in folders_list: folders_list.append(child)
return folders_list