# How to reshape a list as another ragged list [duplicate]

### Background

If I want wo reshape list1 as list2:

list1 = {1, 2, 3, 4, 5, 6};
list2 = {{7, 4}, {1, 7}, {7, 6}};


We can use ArrayReshape and Dimensions to do it.

ArrayReshape[list1, Dimensions[list2]]


{{1, 2}, {3, 4}, {5, 6}}

### Question

But when the list2 is a ragged list,how to do such thing with elegant method?

list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ragList = {{1, 2, 3}, {4, {5, 6}, 7}, {8}, {{{9}}, 10}};

• Try using Flatten. – L.K. Feb 17 '17 at 21:49
• @L.K. I mean how to make list to be ragList as its dimension – yode Feb 17 '17 at 21:51
• @andre Do mind post it as an answer? – yode Feb 17 '17 at 22:22
• I cast my close vote for the wrong question; I meant to mark this as a duplicate of (30405) – Mr.Wizard Feb 18 '17 at 13:12
• @Mr.Wizard It's hard for me to find those relevant post.I'm very sad about this every time. – yode Feb 18 '17 at 13:30

You can do this :

list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ragList = {{a, b, c}, {d, {e, f}, g}, {h}, {{{i}}, j}};

i=1;
Map[list[[i++]]&,ragList,{-1}]


Assuming that the elements in ragList are unique, this would work as well:

ragList /. Map[#[[1]] -> #[[2]] &, Transpose[{Flatten[ragList], Flatten[list]}]]
(* {{1, 2, 3}, {4, {5, 6}, 7}, {8}, {{{9}}, 10}} *)

template = {{a, b, c}, {d, {e, f}, g}, {h}, {{{i}}, j}};
replist = Evaluate[(ReplacePart[template,
Rule @@@ Transpose[{
Reap[MapIndexed[Sow@#2 &, template, {-1}]][[2, 1]],
Slot /@ Range@Length@Flatten@template}]] )] &


{{#1, #2, #3}, {#4, {#5, #6}, #7}, {#8}, {{{#9}}, #10}} &

list = Range@10;
replist@(Sequence @@ list)


{{1, 2, 3}, {4, {5, 6}, 7}, {8}, {{{9}}, 10}}

• But how to get your ragList? – yode Feb 17 '17 at 22:32
• On the other hand, if you will be doing this reshaping for many lists but the same ragList, then something along these lines might be much faster. – Carl Woll Feb 17 '17 at 22:43

Curent method:

reshape[list_, ragList_] :=
Module[{pos = Position[ragList, _?NumericQ, Infinity]},


Usage:

reshape[list, ragList]


{{1, 2, 3}, {4, {5, 6}, 7}, {8}, {{{9}}, 10}}

### Performance

Function andre from this comment

andre[list_, ragList_] :=
Module[{i = 1}, Map[list[[i++]] &, ragList, {-1}]]

MyPlot[{reshape @@ # &,
andre@@ # &}, {Range[#],
MapAt[List, Range[#],
List /@ RandomSample[Range[#], RandomInteger[#]]]} &, 11]


Ps:My MyPlot is MyPlot:=BenchmarkPlot[##1,IncludeFits->True]&