【问题标题】:How to do two-level nested map如何做两级嵌套map
【发布时间】:2015-08-03 10:10:39
【问题描述】:

这是我的代码:

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

如何做两级嵌套map并输出相同的结果。

【问题讨论】:

  • 你的预期输出是什么?

标签: python list python-2.7 dictionary


【解决方案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'}]
>>> 

【讨论】:

    猜你喜欢
    • 2012-05-09
    • 2018-04-25
    • 2014-06-22
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2010-10-06
    • 2019-09-07
    • 1970-01-01
    相关资源
    最近更新 更多