2015-08-03 62 views
0

这是我的代码:怎么办二级嵌套的地图

html_tags = [{'tag': 'a', 
       'attribs': [('class', 'anchor'), 
          ('aria-hidden', 'true')]}] 

我只是一个级别做for循环和一级映射如下:

for index, tag in enumerate(html_tags): 
    html_tags[index]['attribs'] = map(lambda x: '@{}="{}"'.format(*x), tag['attribs']) 
print html_tags 

但是,这是我的输出(结果):

[{'attribs': ['@class="anchor"', '@aria-hidden="true"'], 'tag': 'a'}] 

如何执行两级嵌套映射并输出相同的结果。

+0

什么是您预期的输出? –

回答

1

我建议字典解析:

>>> html_tags = [{i:map(lambda x: '@{}="{}"'.format(*x), j) if i=='attribs' else j for i,j in html_tags[0].items()}] 
>>> html_tags 
[{'attribs': ['@class="anchor"', '@aria-hidden="true"'], 'tag': 'a'}] 
>>> 

而是采用maplambda,你可以使用列表理解更有效的方式也:

>>> html_tags = [{i:['@{}="{}"'.format(*x) for x in j] if i=='attribs' else j for i,j in html_tags[0].items()}] 
>>> html_tags 
[{'attribs': ['@class="anchor"', '@aria-hidden="true"'], 'tag': 'a'}] 
>>>