【问题标题】:Python - generating parent/child dict structurePython - 生成父/子字典结构
【发布时间】:2016-10-02 13:14:58
【问题描述】:

我有方法:

@staticmethod
def get_blocks():
    """Public method that can be extended to add new blocks.

    First item is the most parent. Last item is the most child.
        Returns:
            blocks (list)
    """
    return ['header', 'body', 'footer']

如 docstring 所述,此方法可以扩展,以特定顺序返回任何类型的块。

所以我想制作一个映射来指示哪个块是彼此的父/子(只关心“最近”的父/子)。

def _get_blocks_mapping(blocks):
    mp = {'parent': {}, 'child': {}}
    if not blocks:
        return mp
    mp['parent'][blocks[0]] = None
    mp['child'][blocks[-1]] = None
    blocks_len = len(blocks)
    if blocks_len > 1:
        mp['parent'][blocks[-1]] = blocks[-2]
        for i in range(1, len(blocks)-1):
            mp['parent'][blocks[i]] = blocks[i-1]
            mp['child'][blocks[i]] = blocks[i+1]
    return mp

如果我们在get_blocks 方法中有三个块,那么结果是这样的:

{
        'parent': {
            'header': None,
            'body': 'header',
            'footer': 'body',
        },
        'child': {
            'header': 'body',
            'body': 'footer',
            'footer': None
        }
    }

它很好用,但对我来说有点 hacky。那么也许有人可以建议一种更好的方法来创建这种映射? (或者也许有一些创建父/子映射的常用方法?使用与我打算使用不同的结构?)

【问题讨论】:

    标签: python list python-2.7 dictionary parent-child


    【解决方案1】:

    您希望成对地循环列表,为您提供自然的父子关系:

    mp = {'parent': {}, 'child': {}}
    if blocks:
        mp['parent'][blocks[0]] = mp['child'][blocks[-1]] = None
        for parent, child in zip(blocks, blocks[1:]):
            mp['parent'][child] = parent
            mp['child'][parent] = child
    

    zip() 在这里将每个块与列表中的下一个块配对。

    演示:

    >>> blocks = ['header', 'body', 'footer']
    >>> mp = {'parent': {}, 'child': {}}
    >>> if blocks:
    ...     mp['parent'][blocks[0]] = mp['child'][blocks[-1]] = None
    ...     for parent, child in zip(blocks, blocks[1:]):
    ...         mp['parent'][child] = parent
    ...         mp['child'][parent] = child
    ...
    >>> from pprint import pprint
    >>> pprint(mp)
    {'child': {'body': 'footer', 'footer': None, 'header': 'body'},
     'parent': {'body': 'header', 'footer': 'body', 'header': None}}
    

    【讨论】:

    • 谢谢。这看起来更优雅。
    猜你喜欢
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2020-11-19
    • 2021-12-20
    相关资源
    最近更新 更多