List Comprehension Question: One to Many Mapping?

beginner zyzhu2000 at gmail.com
Fri Aug 24 09:34:23 EDT 2007


On Aug 24, 5:47 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Boris Borcic <bbor... 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.

Not so werid. :-) Just to put this into context, I have a list of list
of objects x=[[o1, o2, o3, o4], [o5,o6]]

I was trying to plot them with matplotlib. Each sub-list is a line. So
I would have to re-organize the list to be like the following:

v=[[o1.x, o2.x, o3.x, o4.x], [o1.y, o2.y, o3.y, o4.y], [o5.x, o6.x],
[o5.y, o6.y]]

So that I can pass it to plot:

plot(*tuple(v))

I like the chain and map solutions.




More information about the Python-list mailing list