If I had a list of let's say 20 elements, how could I split it into two separate lists that contain every other 5 elements of the initial list?
For example:
list={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
function[list]
(*
{1,2,3,4,5,11,12,13,14,15}
{6,7,8,9,10,16,17,18,19,20}
*)
Follow-up question:
Thanks to the numerous answers! Is there a way to revert this process? Say we start from two lists and I would like to end up with the list
above:
list1={1,2,3,4,5,11,12,13,14,15}
list2={6,7,8,9,10,16,17,18,19,20}
function[list1,list2]
(*
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
*)
Answer
ClearAll[f1, f2]
f1[lst_, k_] := Join @@ Partition[lst[[# ;;]], k, 2 k, 1, {}] & /@ {1, k + 1}
{list1, list2} = f1[list, 5]
{{1, 2, 3, 4, 5, 11, 12, 13, 14, 15},
{6, 7, 8, 9, 10, 16, 17, 18, 19, 20}}
An alternative way using the (still undocumented) 6th argument of Partition
:
ClearAll[f1, f2]
f2[lst_, k_] := Partition[Drop[lst, #], k, 2 k, 1, {}, Sequence] & /@ {0, k}
{list1, list2} = f2[list, 5]
{{1, 2, 3, 4, 5, 11, 12, 13, 14, 15},
{6, 7, 8, 9, 10, 16, 17, 18, 19, 20}}
Update: To revert the process:
ClearAll[fb]
fb[lst1_, lst2_, k_] := Join @@ Riffle @@ (Partition[#, k, k, 1, {}] & /@ {lst1, lst2})
fb[list1, list2, 5]
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
Comments
Post a Comment