List Comprehension Question: One to Many Mapping?
Paul Rubin
http
Fri Aug 24 06:47:43 EDT 2007
Boris Borcic <bborcic at gmail.com> writes:
> >> For example, if I have x=[ [1,2], [3,4] ]
> >>
> >> What I want is a new list of list that has four sub-lists:
> >>
> >> [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]]
> > [[a, map(f,a)] for a in x]
>
> no, that one will be [[[1,2], [f(1), f(2)]], [[3,4], [f(3), f(4)]]]
> eg two sublists instead of four.
Oh ugh, I misread the original request and thought the extra brackets
were there. I think the following works and is reasonably intuitive:
from itertools import chain
y = list(chain(*([a, map(f,a)] for a in x)))
But the original request itself seems a bit weird.
More information about the Python-list
mailing list