fthon中的python列表理解

时间:2016-10-08 15:34:25

标签: python list python-2.7 for-loop list-comprehension

考虑我在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是什么?

2 个答案:

答案 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