3

How to re-arrange following list:

{a1,b1,a2,b2,a3,b3,a4,b4} or this {a1,b1},{a2,b2},{a3,b3},{a4,b4}

to get:

{a1,a2,a3,a4},{b1,b2,b3,b4}

so divide a list into 2 lists of rearranging step=2, each second element

funykcheff
  • 33
  • 3
  • Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. – bbgodfrey Apr 18 '15 at 12:12
  • Closed as a duplicate for the first case; simply use Transpose for the second. – Mr.Wizard Apr 18 '15 at 16:22

2 Answers2

4
l1 = {a1, b1, a2, b2, a3, b3, a4,  b4} ;
l2 = {{a1, b1}, {a2, b2}, {a3, b3}, {a4, b4}};

Transpose[ArrayReshape[#, {4, 2}]] &@l1
(* {{a1, a2, a3, a4}, {b1, b2, b3, b4}} *)

Transpose[ArrayReshape[#, {4, 2}]] &@l2
(* {{a1, a2, a3, a4}, {b1, b2, b3, b4}} *)

Also

Flatten[l1][[# ;; ;; 2]] & /@ {1, 2}
(* {{a1, a2, a3, a4}, {b1, b2, b3, b4}}*)

Flatten[l2][[# ;; ;; 2]] & /@ {1, 2}
(* {{a1, a2, a3, a4}, {b1, b2, b3, b4}} *)

For l2 only:

Thread[l2]
(* {{a1, a2, a3, a4}, {b1, b2, b3, b4}} *)

Flatten[l2, {{2}, {1}}]
(* {{a1, a2, a3, a4}, {b1, b2, b3, b4}} *)
kglr
  • 394,356
  • 18
  • 477
  • 896
4

2nd list:

Transpose[{{a1, b1}, {a2, b2}, {a3, b3}, {a4, b4}}]

1st list can be transformed into the second list and then handled the same way:

Transpose[Partition[{a1, b1, a2, b2, a3, b3, a4, b4}, 2]]

It can also be done with Part ([[ ]]):

l1 = {{a1, b1}, {a2, b2}, {a3, b3}, {a4, b4}};
{l1[[All, 1]], l1[[All, 2]]}

l2 = {a1, b1, a2, b2, a3, b3, a4, b4};
{l2[[1 ;; ;; 2]], l2[[2 ;; ;; 2]]}

This is not recommended for this situation, but it's good to know :)

C. E.
  • 70,533
  • 6
  • 140
  • 264