Re: Re: Transforming a list
- To: mathgroup at smc.vnet.net
- Subject: [mg103171] Re: [mg103130] Re: [mg103108] Transforming a list
- From: "David Park" <djmpark at comcast.net>
- Date: Thu, 10 Sep 2009 07:16:26 -0400 (EDT)
- References: <200909080958.FAA26578@smc.vnet.net> <2159159.1252487919233.JavaMail.root@n11>
Thomas, I can't believe that all of us missed your simple solution! And it is right there in Flatten Help. But this is something that probably came with Version 6 and what with all the other new things slipped through the net of awareness. And the problem doesn't initially lead us to Flatten. These level manipulations always make my head spin. This also occurs with the Transpose and Trace commands, and when contracting on arbitrary levels in tensors. For didactic purposes, one way to help understand these level manipulation problems is to attach position indices to the elements using the MapIndexed command. Then we can better see what is happening. So for your solution we could write: lst = {{c, e, g}, {d, f}, {e, g}, {f}, {g}, {}}; (lst2 = MapIndexed[Subscript[#1, Row@#2] &, lst, {2}]) // MatrixForm Flatten[lst2, {{2}, {1}}] // MatrixForm Another case is one of the examples in the Help for Flatten: (u = {{a, b}, {c, d}}) // MatrixForm (tmat = {{u, 0 u}, {0 u, u}}) // MatrixForm (tmat2 = MapIndexed[Subscript[#1, Row@#2] &, tmat, {4}]) // MatrixForm Flatten[tmat2, {{1, 3}, {2, 4}}] // MatrixForm The first and third levels are combined into the first level (the rows) and they cycle through Tuples[{1,2},2] or {11,12,21,22}. For comparison we could do Flatten[tmat2, {{1, 2}, {3, 4}}] // MatrixForm which makes each row the flattened submatrices. David Park djmpark at comcast.net http://home.comcast.net/~djmpark/ From: Thomas Dowling [mailto:thomasgdowling at gmail.com] Hello, lst = {{c, e, g}, {d, f}, {e, g}, {f}, {g}, {}}; In[116]= Flatten[lst, {{2}, {1}}] Out[116]= {{c, d, e, f, g}, {e, f, g}, {g}} >From Carl Woll originally, I think. Good luck Tom Dowling On Tue, Sep 8, 2009 at 10:58 AM, Don <donabc at comcast.net> wrote: > I am given: lst = {{c, e, g}, {d, f}, {e, g}, {f}, {g}, {}} > > I want to form a list of sublists where the first sublist consists of the > first elements > from each sublist of lst, the second sublist the second elements from each > of the sublists of lst etc. > > The final outcome should be: > {{c, d, e, f, g}, {e, f, g}, {g}} > > I can do this by first padding the sublists of lst (to make them the same > length)and then using Transpose. But how to get rid of the trailings 0's? > > For example: > > newLst = Map[PadRight[#, Length[lst[[1]]]] &, lst] > > Transpose[newLst] > > which produces: > > {{c, d, e, f, g, 0}, {e, f, g, 0, 0, 0}, {g, 0, 0, 0, 0, 0}} > > Is there a better way to end up with > > {{c, d, e, f, g}, {e, f, g}, {g}} > > Thank you. > >
- References:
- Transforming a list
- From: Don <donabc@comcast.net>
- Transforming a list