Python递归追加列表函数 [英] Python recursively appending list function
问题描述
递归函数有问题,本应相对简单,但似乎无法正确执行.
Having issues with a recursive function that should be relatively simple to do, but can`t seem to get right.
我有一个文件夹结构,其中的文件夹可以包含其他文件夹、图像或文件.每个文件夹都有关联的权限.我想让我的函数递归地构建一个与每个文件夹关联的权限列表.
I have a folder structure with folders that can contain other folders, images or files. Associated with each folder there are permissions. I want to have my function recursively build a list of the permissions that are associated with each folder.
我有一个函数 has_read_permission(request)
如果文件夹有权限则返回 True
,否则返回 False
I have a function has_read_permission(request)
that returns True
if the folder has permissions and False
if not
我已经构建了一个这样的函数:
I have built a function like so:
def get_child_perms(self, folder, request, perm_list):
# Folder contains other folders
if folder.get_children():
# For every sub-folder
for subfolder in folder.get_children():
return perm_list.append(self.get_child_perms(subfolder, request, perm_list))
else:
# If folder doesn't have sub-folders containing folders
return [folder.has_read_permission(request)]
我一直没有
给定的文件夹如下:
Folder (allowed) - Wont check this one
|_First Folder (allowed)
| |_First sub Folder (restricted)
| | |_File
| | |_File
| | |_Image
| |__Second Sub Folder (allowed)
|_Second Folder (allowed)
然后运行 get_child_perms()
将返回[真,假,真,真]甚至[真,[假,真],真]
Then running get_child_perms()
would return
[True,False,True,True]
or even
[True, [False, True], True]
编辑
忽略编辑 -> 询问其他问题 Python 递归函数缺失结果
Disregard edit -> asked other question Python Recursive function missing results
变身了,
def get_child_perms(self, folder, request, perm_list):
if folder.get_children():
for subfolder in folder.get_children():
perm_list.append(self.get_child_perms(subfolder, request, perm_list))
return perm_list
else:
return [folder.has_read_permission(request)]
得到:
[[True], [...], [True], [...], [...], [True], [True], [True], [True], [True], [True], [True], [True], [...], [True], [...]]
Admin
-Folder 1
- Files
-Folder 2
- Files
-Folder 3
- Files
-Folder 4
- SubFolder 1
-SubSubFolder 1
- Files
- Files
- SubFolder 2
- SubSubFolder 2
- Files
- Files
-Folder 5
- SubFolder 3
- Files
- SubFolder 4
- Files
- SubFolder 5
-Files
- Files
-Folder 6
- Files
-Folder 7
- SubFoler 6
- Files
- Files
-Folder 8
- Files
推荐答案
正如所指出的 append 是一个 inplace 操作,它返回 None,你可以完全避免使用 append
通过返回一个列表组合:
As pointed out append is an inplace operation that returns None, you can avoid using append
at all by returning a list comp:
def get_child_perms(self, folder, request, perm_list):
# Folder contains other folders
children = folder.get_children()
if children:
# For every sub-folder
return [self.get_child_perms(subfolder, request, perm_list)
for subfolder in children]
return [folder.has_read_permission(request)]
你也不需要 else 因为你只能从函数中返回一次.
You don't need an else either as you can only return once from the function.
这篇关于Python递归追加列表函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!