【发布时间】:2021-01-06 04:37:21
【问题描述】:
我是一名初级程序员,刚开始学习嵌套列表和字典。我的任务是创建一个文件系统,包含目录类及其属性。
class Directory:
def __init__(self, name: str, parent: Optional['Directory'], children: List[Optional['Directory']]):
self.name = name
self.parent = parent
self.children = children
我应该构建一个函数来递归地创建这个文件系统,给定根目录及其字典中的目录。 Parent 是一个目录,其中包含当前目录作为他的孩子之一。任何没有子目录的目录都应该是一个空目录。
"root": ["dirA", "dirB"],
"dirA": ["dirC"],
"dirC": ["dirH", "dirG"],
"dirB": ["dirE"]
"dirG": ["dirX", "dirY"]}
我一直在尝试这样做,我想我知道如何递归地创建目录,但是我不知道在没有任何额外导入的情况下将什么放在 dir.parent 位置。使用root,没有问题,因为它是 None 但在进一步的过程中,我不知道如何将孩子的父母(应该是目录)作为他的属性之一,因为我将从那里递归。你知道怎么做吗?这是我到目前为止的代码:
def create_system(system: Dict[str, List[str]], parent_children: List[str]) -> Optional[List[Optional['Directory']]]:
children: List[Optional['Directory']] = []
for child in parent_children:
if child in system.keys():
children.append(Directory(child, parent, create_system(system, list(system.get(child)))))
else:
children.append(Directory(child, parent, []))
return children
def root(system: Dict[str, List[str]]) -> Optional['Directory']:
return Directory("root", None, create_system(system, list(system.get("root"))))
感谢您的回复!
【问题讨论】:
-
Python 对空格非常敏感。请修正你的缩进。
-
我假设您使用
os.mkdir来实际创建目录?你也可以os.mkdirs吗? -
@谢谢。这看起来像一个抽象的数据操作。 “目录”在此上下文中并不表示实际的文件系统目录。
-
也许我误解了这个问题。 @MadPhysicist 你可能是对的,但我会留下我的答案,以防它对其他人有用。