3

想象一下这个对象:

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没有定义。我该怎么做??

4

2 回答 2

6
tags = set(tag  for e in my_obj['Episodes'] for tag in e['Tags'])

您需要更改订单并先获取e ... :)

于 2012-10-05T04:46:35.893 回答
3

我用来避免被这些嵌套推导混淆的技巧是按照循环在推导中出现的顺序展开循环

所以在你的例子中,你有一个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']

正如您已经从之前的答案中看到的那样。希望这可以帮助!

于 2012-10-05T05:20:53.040 回答