考虑我在python list comprehension中嵌套了for循环
>>> data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> [y for x in data for y in x]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> [y for y in x for x in data]
[6, 6, 6, 7, 7, 7, 8, 8, 8]
我无法解释为什么当我改变两个fors
的顺序时
for y in x
第二个列表理解中的x
是什么?
答案 0 :(得分:6)
它持有前一个comprehsension的值。尝试反转它们,您将收到错误
>>> data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> [y for y in x for x in data]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
要进一步测试,请打印x
并查看
>>> [y for x in data for y in x]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> x
[6, 7, 8]
>>> [y for y in x for x in data]
[6, 6, 6, 7, 7, 7, 8, 8, 8]
答案 1 :(得分:2)
列表推导如下:
[y for x in data for y in x]
[y for y in x for x in data]
for
的{{1}}循环转换为:
[y for y in x for x in data]
此处for y in x:
for x in data:
y
保留了您之前列表理解的x
的最新更新值,该值为:
x