你如何在python中进行长列表推导?

时间:2013-08-09 18:47:47

标签: python list-comprehension

例如:

>>> [x for x in range(y) for y in range(z) for z in range(3)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

我希望这行为与:

相同
>>> a=[]
>>> for z in range(3):
...   for y in range(z):
...     for x in range(3):
...       a.append(x)
... 
>>> a
[0, 1, 2, 0, 1, 2, 0, 1, 2]

但事实并非如此。为什么呢?

3 个答案:

答案 0 :(得分:4)

将循环放在传统for循环中的顺序:

>>> [x for z in range(3) for y in range(z) for x in range(3)]
[0, 1, 2, 0, 1, 2, 0, 1, 2]

答案 1 :(得分:4)

如果颠倒循环的顺序,您当前的理解将起作用:

[x for z in range(3) for y in range(z) for x in range(3)]

答案 2 :(得分:3)

你可以这样想出列表理解:

[x for z in range(3)
       for y in range(z)
         for x in range(3) ]

只需删除冒号,将for循环包裹在括号中,并在前面放置x