繁体   English   中英

两层嵌套地图怎么办

[英]How to do two-level nested map

这是我的代码:

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

我可以通过一级for循环和一级map来做到这一点,如下所示:

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

如何做两层嵌套地图并输出相同的结果。

我建议一个字典理解:

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

另外,可以使用列表lambda来代替使用带有lambda map作为更有效的方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM