Re: Transforming a list
- To: mathgroup at smc.vnet.net
- Subject: [mg103129] Re: [mg103108] Transforming a list
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Wed, 9 Sep 2009 04:40:44 -0400 (EDT)
- References: <200909080958.FAA26578@smc.vnet.net>
Hi,
In[1] =
lst = {{c, e, g}, {d, f}, {e, g}, {f}, {g}, {}};
Here are two ways that use your original code:
In[2] =
Module[{q},
Transpose[Map[PadRight[#, Length[lst[[1]]], q] &, lst]] /.
q :> Sequence[]]
Out[2] = {{c, d, e, f, g}, {e, f, g}, {g}}
In[3] =
SplitBy[Most@
ArrayRules@
SparseArray[
Transpose@Map[PadRight[#, Length[lst[[1]]]] &, lst]], #[[1,
1]] &][[All, All, 2]]
Out[3] = {{c, d, e, f, g}, {e, f, g}, {g}}
Two more ways:
In[4] =
Module[{n = 0},
Reap[FixedPoint[
Replace[n++; #, {x_, y___} :> (Sow[x, n]; {y}), 1] &, lst]]
][[2]]
Out[4] = {{c, d, e, f, g}, {e, f, g}, {g}}
In[5] = Most@Reap[
NestWhile[(Sow[#[[All, 1]]]; #[[All, 2 ;;]]) &[# /. {} ->
Sequence[]] &, lst, # =!= {} &]][[2, 1]]
Out[5] = {{c, d, e, f, g}, {e, f, g}, {g}}
Regards,
Leonid
On Tue, Sep 8, 2009 at 1:58 PM, 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