【发布时间】: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