列表理解版本的“扩展”

时间:2018-11-07 22:27:14

标签: python list-comprehension

是否存在以下内容的1-liner等效项(使用列表推导):

a = []
for i in range(6):
    a.extend(((-i,i,0,2),(-i-1,i,0,6)))
a = tuple(a)

我在想类似

tuple(((-i,i,0,2),(-i-1,i,0,6)) for i in range(6))

但这给出了:

(((0, 0, 0, 2), (-1, 0, 0, 6)),
 ((-1, 1, 0, 2), (-2, 1, 0, 6)),
 ((-2, 2, 0, 2), (-3, 2, 0, 6)),
 ((-3, 3, 0, 2), (-4, 3, 0, 6)),
 ((-4, 4, 0, 2), (-5, 4, 0, 6)),
 ((-5, 5, 0, 2), (-6, 5, 0, 6)))

这不是我想要的。

所需的输出

((0, 0, 0, 2),
 (-1, 0, 0, 6),
 (-1, 1, 0, 2),
 (-2, 1, 0, 6),
 (-2, 2, 0, 2),
 (-3, 2, 0, 6),
 (-3, 3, 0, 2),
 (-4, 3, 0, 6),
 (-4, 4, 0, 2),
 (-5, 4, 0, 6),
 (-5, 5, 0, 2),
 (-6, 5, 0, 6))

1 个答案:

答案 0 :(得分:8)

您可以使用嵌套列表推导。

>>> [t for i in range(6) for t in ((-i,i,0,2), (-i-1,i,0,6))]
>>> 
[(0, 0, 0, 2),
 (-1, 0, 0, 6),
 (-1, 1, 0, 2),
 (-2, 1, 0, 6),
 (-2, 2, 0, 2),
 (-3, 2, 0, 6),
 (-3, 3, 0, 2),
 (-4, 3, 0, 6),
 (-4, 4, 0, 2),
 (-5, 4, 0, 6),
 (-5, 5, 0, 2),
 (-6, 5, 0, 6)]

它是这样的

[what I want (t) | for loops as if writing non-listcomp code]

因此等同于

result = []
for i in range(6):
    for t in ((-i,i,0,2), (-i-1,i,0,6)):
        result.append(t)