连接预定义数据结构的序列
我一直在努力构建这段代码,我想知道是否还有其他更简单/有效的方法来执行此操作:
fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}}
def __buildPathFromSchema(self, schema, root=''):
metaDirs = []
for dir_ in schema.keys():
root = os.path.join(root, dir_)
if isinstance(schema[dir_], dict):
return self.__buildPathFromSchema(schema[dir_], root)
if isinstance(schema[dir_], tuple):
for i in schema[dir_]:
bottom = os.path.join(root, i)
metaDirs.append(bottom)
root = os.sep.join(os.path.split(root)[:-1])
return metaDirs
基本上我想要做的是从 fsSchema 等预定义结构生成路径。请注意,最新的迭代始终是一个元组。
输出看起来像:
['已发布\渲染\REN\fold1', '已发布\渲染\REN\fold2', '已发布\渲染\SIM\fold1', '已发布\渲染\SIM\fold2']
谢谢!
I've been struggling a little to build this piece of code, and I was wondering if there are others more simple/efficient way of doing this:
fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}}
def __buildPathFromSchema(self, schema, root=''):
metaDirs = []
for dir_ in schema.keys():
root = os.path.join(root, dir_)
if isinstance(schema[dir_], dict):
return self.__buildPathFromSchema(schema[dir_], root)
if isinstance(schema[dir_], tuple):
for i in schema[dir_]:
bottom = os.path.join(root, i)
metaDirs.append(bottom)
root = os.sep.join(os.path.split(root)[:-1])
return metaDirs
Basically what I want to do is generating paths from a predefined structure like fsSchema. Note the latest iteration is always a tuple.
The ouput looks like:
['published\renders\REN\fold1',
'published\renders\REN\fold2',
'published\renders\SIM\fold1',
'published\renders\SIM\fold2']
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用递归函数来生成所有路径:
这应该能够处理任何类型的嵌套字典:
请注意,路径是按“随机”顺序生成的,因为字典没有任何内部排序。
You can use a recursive function to generate all the paths:
This should be able to handle any kind of nested dictionaries:
Note that the paths are generated in "random" order since dictionaries don't have any internal ordering.
而不是:
你可以这样做:
它更快,更具可读性。
Instead of:
you can do:
It's both faster and more readable.
我会像您一样继续递归地执行此操作,但将步行器与路径生成器分开:
原因是它实际上是两个独立的功能部分,并且将它们实现为单独的函数,因此更容易调试、维护、实现,并且只是一般都会想到。
I would keep doing it recursively like you already are but split the walker off from the path generator:
The reason being that it is really two separate pieces of functionality and having them implemented as separate functions is hence easier to debug, maintain, implement and just generally think about.