List comprehension version of “extend” [duplicate]

2019-02-24 18:23发布

Is there a 1-liner equivalent (using list comprehension) for the following:

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

I was thinking something like

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

but this gives:

(((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)))

which is not what I want.

Desired output

((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条回答
做自己的国王
2楼-- · 2019-02-24 18:41

You can use a nested list comprehension.

>>> [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)]

It reads like this

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

and is thus equivalent to

result = []
for i in range(6):
    for t in ((-i,i,0,2), (-i-1,i,0,6)):
        result.append(t)
查看更多
登录 后发表回答