List comprehension version of “extend” [duplicate]

2019-02-24 18:49发布

问题:

This question already has an answer here:

  • How to use list comprehension with .extend list method? [duplicate] 2 answers
  • How can I use a list comprehension to extend a list in python? [duplicate] 6 answers
  • Python: How to extend or append multiple elements in list comprehension format? 2 answers

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:

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)