练习 - 帮助调试嵌套列表理解

我有一本字典,如:


output = {'all_paths': [{'path': [{'to': '59v4aQo015zRyeGZ', 'proximity': 6, 'from': '4Po9aW3oxoNaAQzW'}], 'weight': 6}, {'path': [{'to': '59v4aQo015zRyeGZ', 'proximity': 7, 'from': 'AyD8rYemY6er47Vk'}, {'to': 'ZGmDayG795LRojPv', 'proximity': 6, 'from': 'AyD8rYemY6er47Vk'}, {'to': '59v4aQo015zRyeGZ', 'proximity': 6, 'from': '4Po9aW3oxoNaAQzW'}, {'to': 'ZGmDayG795LRojPv', 'proximity': 6, 'from': '4Po9aW3oxoNaAQzW'}, {'to': '59v4aQo015zRyeGZ', 'proximity': 6, 'from': 'eEo7aB0vgkdRO02V'}, {'to': 'ZGmDayG795LRojPv', 'proximity': 4, 'from': 'eEo7aB0vgkdRO02V'}], 'weight': 35}, {'path': [{'to': 'LWbARpjEjpZae3DZ', 'proximity': 4, 'from': '4Po9aW3oxoNaAQzW'}, {'to': '59v4aQo015zRyeGZ', 'proximity': 6, 'from': '4Po9aW3oxoNaAQzW'}], 'weight': 10}, {'path': [{'to': 'ZGmDayG795LRojPv', 'proximity': 6, 'from': '4Po9aW3oxoNaAQzW'}], 'weight': 6}, {'path': [{'to': 'LWbARpjEjpZae3DZ', 'proximity': 4, 'from': '4Po9aW3oxoNaAQzW'}], 'weight': 4}, {'path': [{'to': 'ZGmDayG795LRojPv', 'proximity': 7, 'from': 'LWbARpjEjpZae3DZ'}], 'weight': 7}]}

我想创建两个集合,一个包含字段“to”中的所有 id,另一个包含字段“from”中的所有 id。


为了简洁起见,我尝试了列表理解,但得到了一个意想不到的结果,只包含一个主题:


nf = set([edge['from'] for edge in path['path'] for path in output['all_paths']])

# set(['LWbARpjEjpZae3DZ'])

正确的结果是:


nf = set()

for edge in [path['path'] for path in output['all_paths']]:

    nf.add( edge[0]['from'])

# set(['AyD8rYemY6er47Vk', '4Po9aW3oxoNaAQzW', 'LWbARpjEjpZae3DZ'])

你能帮助指出我的嵌套列表理解有什么问题吗?


子衿沉夜
浏览 146回答 2
2回答

心有法竹

您可以使用嵌套理解:d = {i.get('from', i.get('id')) for b in output['all_paths'] for i in b['path']}输出:{'LWbARpjEjpZae3DZ', 'eEo7aB0vgkdRO02V', 'AyD8rYemY6er47Vk', '4Po9aW3oxoNaAQzW'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python