List of Understanding Questions

Is there a way to add multiple items to a list in a list comprehension per iteration? For instance:

y = ['a', 'b', 'c', 'd']
x = [1,2,3]

return [x, a for a in y]

conclusion: [[1,2,3], 'a', [1,2,3], 'b', [1,2,3], 'c', [1,2,3], 'd']

+5
source share
3 answers

I am sure that there is, but not with a clear understanding of the list:

EDIT: Inspired by another answer:

y = ['a', 'b', 'c', 'd']
x = [1,2,3]

return sum([[x, a] for a in y],[])

How it works: sum will add a sequence of anythings as long as there is an element __add__to do the job. BUT, it starts with an initial total of 0. You cannot add 0 to the list, but you can give a sum()different initial value. Here we use an empty list.

, itertools.chain.from_iterable, .

from itertools import *

return chain.from_iterable((x,a) for a in y)

itertools:

return itertools.chain.from_iterable(itertools.izip(itertools.repeat(x),y))
, : , :
return reduce(list.__add__,([x, a] for a in y))

, , . , map list.extend:

l = []
map(l.extend,[[x, a] for a in y])
return l

, , :

return [ y[i/2] if i%2 else x for i in range(len(y)*2)]
+6

:

y = ['a', 'b', 'c', 'd']
x = [1,2,3]

return reduce(lambda a,b:a+b, [[x,a] for a in y])
+1
x = [1,2,3]
y = ['a', 'b', 'c', 'd']
z = []

[z.extend([x, a]) for a in y]

(The correct value will be in z)

+1
source

All Articles