python循环功能_Python中的递归循环功能

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.

Assuming I have a function called getChildFolders(), what is the most efficient way to call this kind of recursive loop?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值