如何做两级嵌套映射

时间:2015-08-03 10:10:40

标签: python list python-2.7 dictionary

这是我的代码:

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'}]

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

1 个答案:

答案 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'}]
>>>