3
$\begingroup$

I am trying to do the partition of the list variable called test so that answer will look like the variable called goal. The test list is actually a list of long data. In this example I have a short version example according to the code below which also includes my attempts called ans1 and ans2 using method called Partition and ArrayShape:

 Clear[ans];
 goal={{{a,b,c},{d,e,f},{g,h,i},j},{{k,l,m},{n,o,p},{q,r,s},t}};
 TableForm[goal]

And the output should be

 a d g
 b e h j
 c f i

 k n q
 l o r t
 m p s

My attempt is:

 test={a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t};
 ans1=Partition[test,3,3,1,Nothing]
 {{a,b,c},{d,e,f},{g,h,i},{j,k,l},{m,n,o},{p,q,r},{s,t}}
 TableForm[ans1]

 ans2=ArrayReshape[test,{3,3,3},1]
 {{{a,b,c},{d,e,f},{g,h,i}},{{j,k,l},{m,n,o},{p,q,r}},{{s,t,1},{1,1,1},{1,1,1}}}
 TableForm[ans2]
$\endgroup$

2 Answers 2

5
$\begingroup$

Edit(reply to comment)

For the pattern {{#,#,#},{#,#,#},{#,#,#},{#,#,#},#},there are 3*4+1 elements, so we use

test = Range[39];
FlattenAt[#, {-1}] & /@ (Partition[#, UpTo[3]] & /@ 
   Partition[test, UpTo[3*4 + 1]])

enter image description here

Original

test={a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t};
FlattenAt[#, {-1}] & /@ (Partition[#, UpTo[3]] & /@ 
   Partition[test, UpTo[10]])

FlattenAt[#, {-1}] & /@ (Partition[#, UpTo[3]] & /@ 
   Partition[test, 10])

FlattenAt[#, {-1}] & /@ (Partition[#, 3, 3, 1, Nothing] & /@ 
   Partition[test, 10])

> {{{a, b, c}, {d, e, f}, {g, h, i},  j}, {{k, l, m}, {n, o, p}, {q, r, s}, t}}

$\endgroup$
2
  • $\begingroup$ Great code.....How do you adjust from (3,3,1) to (3,4,1)? Or originally 3 vectors (of 3variables) and scalar to 4 vectors (3 variables) and scalar. {{{a,b,c},{d,e,f},{g,h,i},{j,k,l}},n},{{o,p,q},{........}} when test list is long. $\endgroup$
    – Aschoolar
    Aug 26, 2022 at 10:49
  • $\begingroup$ @Aschoolar Use FlattenAt[#, {-1}] & /@ (Partition[#, UpTo[3]] & /@ Partition[test, UpTo[4*3 + 1]]) Or FlattenAt[#, {-1}] & /@ (Partition[#, 3, 3, 1, Nothing] & /@ Partition[test, 4*3 + 1]) $\endgroup$
    – cvgmt
    Aug 26, 2022 at 11:35
3
$\begingroup$

Assuming that the number of items in test is not divisible by the total number of elements in each partition, e.g.,

test = {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,
    v, w, x, y};

a possible solution using TakeList can be:

FlattenAt[#, {4}] & /@ (TakeList[#, UpTo /@ {3, 3, 3, 1}] & /@ 
   Partition[test, UpTo[10]])
{{{a, b, c}, {d, e, f}, {g, h, i}, 
  j}, {{k, l, m}, {n, o, p}, {q, r, s}, t}, {{u, v, w}, {x, y}, {}}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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