List Comprehension Question: One to Many Mapping?

beginner zyzhu2000 at gmail.com
Fri Sep 14 18:53:12 EDT 2007


On Aug 24, 5:35 am, Boris Borcic <bbor... at gmail.com> wrote:
> Paul Rubin wrote:
> > beginner <zyzhu2... 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.
>
> [map(g,a) for a in x for g in [None,f]]
>
> will do it.
>
> ...a bit too cleverly, but there's worse :
>
> list((yield a) or map(f,a) for a in x)
>
> Cheers, BB

Really cool!




More information about the Python-list mailing list