Name not defined in multi-cycle list comprehension

I try to unpack a complex dictionary, and I get a NameError in a list comprehension expression using a few 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 
+5
source share
1 answer

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

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

Now g defined for the next for r in a[g] loop, and the expression no longer throws 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] 
+7
source

Source: https://habr.com/ru/post/1243315/


All Articles