连接预定义数据结构的序列

发布于 2024-09-25 22:34:10 字数 877 浏览 2 评论 0原文

我一直在努力构建这段代码,我想知道是否还有其他更简单/有效的方法来执行此操作:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

感受沵的脚步 2024-10-02 22:34:10

您可以使用递归函数来生成所有路径:

def flatten(data):
   if isinstance(data, tuple):
      for v in data:
         yield v
   else:
      for k in data:
         for v in flatten(data[k]):
            yield k + '\\' + v

这应该能够处理任何类型的嵌套字典:

>>> fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}}
>>> list(flatten(fsSchema))
['published\\renders\\REN\\fold1', 'published\\renders\\REN\\fold2', 'published\\renders\\SIM\\fold1', 'published\\renders\\SIM\\fold2']

请注意,路径是按“随机”顺序生成的,因为字典没有任何内部排序。

You can use a recursive function to generate all the paths:

def flatten(data):
   if isinstance(data, tuple):
      for v in data:
         yield v
   else:
      for k in data:
         for v in flatten(data[k]):
            yield k + '\\' + v

This should be able to handle any kind of nested dictionaries:

>>> fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}}
>>> list(flatten(fsSchema))
['published\\renders\\REN\\fold1', 'published\\renders\\REN\\fold2', 'published\\renders\\SIM\\fold1', 'published\\renders\\SIM\\fold2']

Note that the paths are generated in "random" order since dictionaries don't have any internal ordering.

泛泛之交 2024-10-02 22:34:10

而不是:

for dir_ in schema.keys():
    ...
    if isinstance(schema[dir_], dict):

你可以这样做:

for dir_name, dir_content in schema.iteritems():
    ...
    if isinstance(dir_content, tuple):

它更快,更具可读性。

Instead of:

for dir_ in schema.keys():
    ...
    if isinstance(schema[dir_], dict):

you can do:

for dir_name, dir_content in schema.iteritems():
    ...
    if isinstance(dir_content, tuple):

It's both faster and more readable.

浅忆流年 2024-10-02 22:34:10

我会像您一样继续递归地执行此操作,但将步行器与路径生成器分开:

def walk(data):
    if hasattr(data, 'items'):
        for outer_piece, subdata in data.items():
            for inner_piece in walk(subdata):
                yield (outer_piece, ) + inner_piece
     else:
         for piece in data:
             yield (piece, )

def paths(data):
    for path in walk(data):
        yield os.sep.join(path)

原因是它实际上是两个独立的功能部分,并且将它们实现为单独的函数,因此更容易调试、维护、实现,并且只是一般都会想到。

I would keep doing it recursively like you already are but split the walker off from the path generator:

def walk(data):
    if hasattr(data, 'items'):
        for outer_piece, subdata in data.items():
            for inner_piece in walk(subdata):
                yield (outer_piece, ) + inner_piece
     else:
         for piece in data:
             yield (piece, )

def paths(data):
    for path in walk(data):
        yield os.sep.join(path)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文