名称未在具有多个循环的列表推导中定义

时间:2016-02-18 11:02:02

标签: python list-comprehension

我试图解压缩复杂词典,并且我在使用多个循环的列表推导表达式中获得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

1 个答案:

答案 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]