我试图解压缩复杂词典,并且我在使用多个循环的列表推导表达式中获得NameError
:
a={
1: [{'n': 1}, {'n': 2}],
2: [{'n': 3}, {'n': 4}],
3: [{'n': 5}],
}
good = [1,2]
print [r['n'] for r in a[g] for g in good]
# NameError: name 'g' is not defined
答案 0 :(得分:11)
你的循环顺序混乱了;它们被认为是从左到右嵌套,因此for r in a[g]
是外部循环并首先执行。换掉循环:
print [r['n'] for g in good for r in a[g]]
现在为下一个循环g
定义for r in a[g]
,表达式不再引发异常:
>>> a={
... 1: [{'n': 1}, {'n': 2}],
... 2: [{'n': 3}, {'n': 4}],
... 3: [{'n': 5}],
... }
>>> good = [1,2]
>>> [r['n'] for g in good for r in a[g]]
[1, 2, 3, 4]