Producing multiple items in a list comprehension
Joel Koltner
zapwireDASHgroups at yahoo.com
Thu May 22 17:03:42 EDT 2008
Hi Marc,
"Marc Christiansen" <usenet at solar-empire.de> wrote in message
news:39vgg5-a9t.ln1 at pluto.solar-empire.de...
> I'm not sure I would recommend it, but try:
> [v for x in range(4) for v in (x, 2 * x)]
That certainly works... and it almost seems like a bit less of a hack (if
perhaps somewhat harder to read) than the "sum" approach to flattening?
> A similar solution as above should work.
This is what I came up with:
>>> list1=[1,2,3]
>>> list2=[4,5,6]
>>> [j for (i,m) in enumerate(list1) for j in (m,list2[i])]
[1, 4, 2, 5, 3, 6]
Not exactly "clean" due to having to enumerate list1 to get the index for
list2. There may be a better method, of course -- so far I like Petter
Otten's approach.
Thanks for the help,
---Joel
More information about the Python-list
mailing list