Python 中的递归循环函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4138851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recursive looping function in Python
提问by andyashton
I have a database that models a foldering relationship to nlevels of nesting. For any given folder, I want to generate a list of all child folders.
我有一个数据库,可以将文件夹关系建模n为嵌套级别。对于任何给定的文件夹,我想生成所有子文件夹的列表。
Assuming I have a function called getChildFolders(), what is the most efficient way to call this kind of recursive loop?
假设我有一个名为 的函数getChildFolders(),那么调用这种递归循环的最有效方法是什么?
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.
以下代码适用于 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)
采纳答案by Jochen Ritzel
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
回答by andyashton
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)
回答by Lloeki
This is the closest to your code, and very unpythonic:
这是最接近您的代码,并且非常不pythonic:
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)
You should probably look for os.walkand take a similar approach to walk the tree iteratively.
您可能应该寻找os.walk并采用类似的方法来迭代地遍历树。
回答by aaronasterling
I generally avoid recursion like the plague in python because it's slow and because of the whole stack overflow error thing.
我通常避免像 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
This assumes that getChildFoldersreturns an empty list when there are no children. If it does something else, like return a sentinel value or raise an exception, then modifications will have to be made.
这假设getChildFolders当没有孩子时返回一个空列表。如果它执行其他操作,例如返回标记值或引发异常,则必须进行修改。
回答by pedrovgp
I needed something similar once to check a hierarchic tree. You could try:
我曾经需要类似的东西来检查层次树。你可以试试:
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

