TransWikia.com

How to Partition rest rows by the first row?

Mathematica Asked on April 28, 2021

Given a list

lst = {{{"1","2","3"},{"4","5"},{"6","7","8","9"}},
        { "A","B","C","D","E","F","G","H","I"},
        { "9","8","7","6","5","4","3","2","1"}};

How to get this by Partition.

res =  {{{"1","2","3"},{"4","5"},{"6","7","8","9"}},
        {{"A","B","C"},{"D","E"},{"F","G","H","I"}},
        {{"9","8","7"},{"6","5"},{"4","3","2","1"}}};

Thanks!

4 Answers

lst2 = lst;
lst2[[2 ;;]] = TakeList[Flatten @ #, Length /@ lst[[1]]] & /@ lst[[2 ;;]];
lst2

{{{"1", "2", "3"}, {"4", "5"}, {"6", "7", "8", "9"}},
{{"A", "B", "C"}, {"D", "E"}, {"F", "G", "H", "I"}},
{{"9", "8", "7"}, {"6", "5"}, {"4", "3", "2", "1"}}}

Also:

lst3 = lst; 
lst3[[2 ;;]] = Function[x, Module[{k = 0}, Map[x[[k++]] &, lst[[1]], {-1}]]] /@ Rest[lst3];
lst3

same result

MapAt[TakeList[Flatten @ #, Length /@ lst[[1]]] &, lst, {2;;}]

same result

Extract[Flatten @ #, List /@ Module[{k = 1}, Map[k++ &, lst[[1]], {-1}]]] & /@ lst

same result

Correct answer by kglr on April 28, 2021

p = Length /@ First[lst];

res = Prepend[
  Internal`PartitionRagged[#, p] & /@ Rest[lst],
  First[lst]]
{{{1, 2, 3}, {4, 5}, {6, 7, 8, 9}},
 {{A, B, C}, {D, E}, {F, G, H, I}},
 {{9, 8, 7}, {6, 5}, {4, 3, 2, 1}}}

Answered by Chris Degnen on April 28, 2021

The following also works. I removed the brackets

Prepend[Table[FoldPairList[TakeDrop, lst[[i]], Length /@ lst[[1]]], {i, 2, Length[lst]}], lst[[1]]]

Also, many thanks to kglr for correcting my code.

FoldPairList[TakeDrop, #, Length /@ lst[[1]]] & /@ Rest[lst]

Answered by Titus on April 28, 2021

We can also use the (undocumented) built-in function Internal`CopyListStructure:

Join[{First @ lst}, Internal`CopyListStructure[First @ lst, #] & /@ Rest @ lst ]
{{{"1", "2", "3"}, {"4", "5"}, {"6", "7", "8", "9"}},
 {{"A", "B", "C"}, {"D", "E"}, {"F", "G", "H", "I"}}, 
 {{"9", "8", "7"}, {"6", "5"}, {"4", "3", "2", "1"}}}

Answered by kglr on April 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP