【发布时间】:2020-04-20 16:25:35
【问题描述】:
我想知道为什么以下列表理解失败 (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
【问题讨论】:
-
列表理解如下
[ 1st loop 2nd for loop 3rd for loop]并在第二个循环中使用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],但y_value来自第三个for循环。