python - 您可以在列表理解中嵌套多少个 for 循环是否有限制?
问题描述
我想知道为什么以下列表理解失败(UnboundLocalError: local variable 'y_value' referenced before assignment
)。如果我在三重嵌套的 for 循环中逐字地拼出 for 循环,我会很好地得到我想要的结果。
for y_value_group in collinear_y_values:
all_y_values = []
for y_value in y_value_group:
for line_id in horizontal_lines[y_value]:
for p in LINES[line_id].pts:
all_y_values.append(p.y)
print(all_y_values)
all_y_values = [p.y for p in LINES[line_id].pts for line_id in horizontal_lines[y_value] for y_value in y_value_group]
print(all_y_values)
给出以下输出:
[-0.01447138307529966, 0.22089181280929138, 0.22089181280929138, 0.19409634248390767]
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-85-62411ee08ee6> in <module>
24 print(all_y_values)
---> 25 all_y_values = [p.y for p in LINES[line_id].pts for line_id in horizontal_lines[y_value] for y_value in y_value_group]
26 print(all_y_values)
<ipython-input-85-62411ee08ee6> in <listcomp>(.0)
24 print(all_y_values)
---> 25 all_y_values = [p.y for p in LINES[line_id].pts for line_id in horizontal_lines[y_value] for y_value in y_value_group]
26 print(all_y_values)
UnboundLocalError: local variable 'y_value' referenced before assignment
解决方案
有点令人困惑的是,在列表理解中,您应该将外循环放在首位:
>>> [x for x in y for y in np.random.random((2,2))]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> [x for y in np.random.random((2,2)) for x in y]
[0.5656047153549479, 0.19139220091114273, 0.10286775868807774, 0.3230695608882298]
所以只需更改顺序:
[
p.y
for y_value in y_value_group
for line_id in horizontal_lines[y_value]
for p in LINES[line_id].pts
]
推荐阅读
- swift - 内存泄漏,尽管没有强引用?
- .htaccess - htaccess 中是否允许额外的空格?
- html - 如何在居中的图像旁边放置文本?
- c# - Docusign api 文件夹:列出未出现的子文件夹
- r - 在 R (libxml2) 中安装 XML 包时出错
- javascript - 2 玩家 Javascript 刽子手游戏问题提示
- c++ - 为什么减法时得到0而不是负数?
- c# - 将 ExpandableObjectConverter 属性分配给属性级别或类级别有什么区别?
- swift - 使用不需要的对象初始化结构对象
- c# - DotNet Core Api - 特定端点的不同身份验证