5
$\begingroup$

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!

$\endgroup$
9
$\begingroup$
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

$\endgroup$
  • $\begingroup$ Thanks! Master who is energetic and always online.;) $\endgroup$ – Jerry Jan 19 at 6:06
3
$\begingroup$
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}}}
$\endgroup$
2
$\begingroup$

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]
$\endgroup$
  • 1
    $\begingroup$ Titus, re "Unfortunately, ..." , just move & outside FoldPairList[...], that is, use FoldPairList[TakeDrop, #, Length /@ lst[[1]]] & /@ Rest[lst]. $\endgroup$ – kglr Jan 19 at 10:10
  • $\begingroup$ @kglr thank you very much! I do not handle pure functions well. $\endgroup$ – Titus Jan 19 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.