Producing multiple items in a list comprehension
Yves Dorfsman
yves at zioup.com
Fri May 23 01:07:57 EDT 2008
Peter Otten <__peter__ at web.de> wrote:
> > A slightly similar problem: If I want to "merge," say, list1=[1,2,3] with
> > list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way with "zip"
> > to do so?
> >>> items = [None] * 6
> >>> items[::2] = 1,2,3
> >>> items[1::2] = 4,5,6
> >>> items
> [1, 4, 2, 5, 3, 6]
My problem with this solution is that you depend on knowing how many
elements you have in each list ahead of time. Assuming that both list
are of the same length, then, I find the following more elegant:
list1=[1,2,3]
list2=[4,5,6]
reduce(lambda x, y: x+y, zip(list1, list2))
of course, zip creates tuples, so you end up with a tuple, therefore if
you need for your solution to be a list:
list(reduce(lambda x, y: x+y, zip(list1, list2)))
of
reduce(lambda x, y: x+y, list(zip(list1, list2)) )
Yves.
http://www.SollerS.ca
More information about the Python-list
mailing list