python - Name is not defined in a list comprehension with multiple loops -
i'm trying unpack complex dictionary , i'm getting nameerror
in list comprehension expression using multiple loops:
a={ 1: [{'n': 1}, {'n': 2}], 2: [{'n': 3}, {'n': 4}], 3: [{'n': 5}], } = [1,2] print [r['n'] r in a[g] g in good] # nameerror: name 'g' not defined
you have order of loops mixed up; considered nested left right, for r in a[g]
outer loop , executed first. swap out loops:
print [r['n'] g in r in a[g]]
now g
defined next loop, for r in a[g]
, , expression no longer raises exception:
>>> a={ ... 1: [{'n': 1}, {'n': 2}], ... 2: [{'n': 3}, {'n': 4}], ... 3: [{'n': 5}], ... } >>> = [1,2] >>> [r['n'] g in r in a[g]] [1, 2, 3, 4]
Comments
Post a Comment