想象一下这个对象:
my_obj = {
'Episodes' : [
{'Tags' : ['one','two','three']},
{'Tags' : ['three','four','five']}
]
}
我想创建一组标签:
tags = set(tag for tag in e['Tags'] for e in my_obj['Episodes'])
但是,它不起作用,因为未定义e
。我该怎么办?
答案 0 :(得分:6)
tags = set(tag for e in my_obj['Episodes'] for tag in e['Tags'])
你需要改变顺序并先获得......:)
答案 1 :(得分:1)
我用来避免被这些嵌套理解混淆的技巧是按照它在理解中出现的顺序展开循环。
因此,在您的示例中,您有一个genex:
tag for tag in e['Tags'] for e in my_obj['Episodes']
你可以在心理上扩展到这样的双循环:
for tag in e['Tags']:
for e in my_obj['Episodes']:
yield tag
现在有了这个结构,你可以清楚地看到你的错误在哪里,e
未定义,并且看到它应该是真的:
for e in my_obj['Episodes']:
for tag in e['Tags']:
yield tag
这会折叠回嵌套理解
tag for e in my_obj['Episodes'] for tag in e['Tags']
正如您从之前的答案中已经看到的那样。希望这有帮助!