Name is not defined in a list comprehension with m

2020-01-27 07:37发布

问题:

I'm trying to unpack a complex dictionary and I'm getting a NameError in a list comprehension expression using multiple loops:

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:

You have the order of your loops mixed up; they are considered nested from left to right, so for r in a[g] is the outer loop and executed first. Swap out the loops:

print [r['n'] for g in good for r in a[g]]

Now g is defined for the next loop, for r in a[g], and the expression no longer raises an exception:

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