簡體   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