build list of lists using comprehension lists two at a time
I am using the following code to build a list of 开发者_如何学Pythonlists:
res = []
for i in I:
res.append(x)
res.append(y[i])
so my final list is [x, y[0], x, y[1],...]
where x
and y[i]
are also lists.
Is there a way building this list using list comprehensions, instead of for loop?
I ... think ... this might be close to what you want:
res = [z for z in ((x, y[i]) for i in I)]
Itertools can help with this sort of thing:
>>> y = I = range(5)
>>> x = 'x'
>>> res = list(itertools.chain.from_iterable((x, y[i]) for i in I))
>>> res
['x', 0, 'x', 1, 'x', 2, 'x', 3, 'x', 4]
res = reduce(tuple.__add__, [(x, y[i]) for i in I])
The map style:
res = []
map(res.extend, ((x, y[i]) for i in I))
The reduce style:
res = reduce(lambda arr, i: arr + [x, y[i]], I, [])
sum(([x, y[i]] for i in I), [])
Like bpgergo's, but with lists, and with a simpler way of joining them together.
I think this should do what you are looking for:
>>> from itertools import chain, izip, repeat
>>> x = [1, 2]
>>> y = [['a', 'b'], ['c', 'd']]
>>> list(chain(*izip(repeat(x), y)))
[[1, 2], ['a', 'b'], [1, 2], ['c', 'd']]
Note that this will have shallow copies of the inner lists (same as other solutions), so make sure you understand the following behavior:
>>> z = list(chain(*izip(repeat(x), y)))
>>> z
[[1, 2], ['a', 'b'], [1, 2], ['c', 'd']]
>>> x.append(3)
>>> z
[[1, 2, 3], ['a', 'b'], [1, 2, 3], ['c', 'd']]
>>> z[0].append(4)
>>> z
[[1, 2, 3, 4], ['a', 'b'], [1, 2, 3, 4], ['c', 'd']]
>>> y[1].append('e')
>>> z
[[1, 2, 3, 4], ['a', 'b'], [1, 2, 3, 4], ['c', 'd', 'e']]
精彩评论