本文介绍了没有在具有多个循环的列表理解中定义名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打开一个复杂的字典,并使用多个循环在列表理解表达式中得到一个NameError
:
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
推荐答案
您将循环的顺序混为一谈;它们被认为是从左到右嵌套的,因此for r in a[g]
是 outer 循环并首先执行.交换循环:
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]]
现在为下一个循环for r in a[g]
定义了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]
这篇关于没有在具有多个循环的列表理解中定义名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!