# Partition sublists of a list

Let's say I have the following list:

l1={{2015, 5, 6, 13692}, {2015, 5, 7, 13715}, {2015, 5, 10,  13274},
{2015, 5, 11, 13581}, {2015, 5, 12, 13609}};


How is it possible to rearrange so it becomes

l2={{{2015, 5, 6}, 13692}, {{2015, 5, 7}, 13715}, {{2015, 5, 10},  13274},
{{2015, 5, 11}, 13581}, {{2015, 5, 12}, 13609}}


That is, I want to partition each sublist of l1 and make it look like l2.

• Composition[Through, {Most, Last}] /@ l1? Commented Aug 8, 2017 at 19:42
• Thanks!!! It works. Commented Aug 8, 2017 at 19:48
• related: 2688
– Kuba
Commented Aug 8, 2017 at 19:51
• Argument destructuring works well in this situation. After defining restructure[{a__, b_}] := {{a}, b}, restructure /@ l1 gives the desired result. Commented Aug 8, 2017 at 20:53

l1 = {{2015, 5, 6, 13692}, {2015, 5, 7, 13715}, {2015, 5, 10, 13274}, {2015, 5, 11, 13581}, {2015, 5, 12, 13609}}

l1 /. {a__, b_?AtomQ} :> {{a}, b}


or

Replace[l1, {a__, b_} :> {{a}, b}, {1}]


{{{2015, 5, 6}, 13692}, {{2015, 5, 7}, 13715}, {{2015, 5, 10}, 13274}, {{2015, 5, 11}, 13581}, {{2015, 5, 12}, 13609}}

Another possibility with Part

{#[[1 ;; 3]], #[[4]]} & /@ l1

• Thanks a lot! Both work. The second answer with 'Replace' is fantastic. I understand it since it's more close to my level! Commented Aug 8, 2017 at 19:55

and a classic:

{{#, #2, #3}, #4} & @@@ l1

l1 // {#[[All, ;; 3]], #[[All, -1]]} & // Transpose


{{{2015, 5, 6}, 13692}, {{2015, 5, 7}, 13715}, {{2015, 5, 10}, 13274}, {{2015, 5, 11}, 13581}, {{2015, 5, 12}, 13609}}

list =
{{2015, 5, 6, 13692}, {2015, 5, 7, 13715}, {2015, 5, 10, 13274},
{2015, 5, 11, 13581}, {2015, 5, 12, 13609}};


Using Comap (new in 14.0)

Comap[{Most, Last}] /@ list


{{{2015, 5, 6}, 13692}, {{2015, 5, 7}, 13715}, {{2015, 5, 10}, 13274}, {{2015, 5, 11}, 13581}, {{2015, 5, 12}, 13609}}

Using Query

Query[All, {Most, Last}] @ list


(* same result *)

list = {{2015, 5, 6, 13692}, {2015, 5, 7, 13715},
{2015, 5, 10, 13274}, {2015, 5, 11, 13581},
{2015, 5, 12, 13609}};


Using SlotSequence and MapApply:

Through[{Most, Last}@{##}] & @@@ list

(*{{{2015, 5, 6}, 13692}, {{2015, 5, 7}, 13715},
{{2015, 5, 10}, 13274}, {{2015, 5, 11}, 13581},
{{2015, 5, 12}, 13609}}*)

l1 = {{2015, 5, 6, 13692}, {2015, 5, 7, 13715}, {2015, 5, 10,
13274}, {2015, 5, 11, 13581}, {2015, 5, 12, 13609}};

FlattenAt[#, -1] &@Partition[#, UpTo[3]] & /@ l1
FlattenAt[#, -1] &@TakeList[#, {3, 1}] & /@ l1
FlattenAt[#, -1] &@TakeDrop[#, 3] & /@ l1
{Take[#, 3], Last@#} & /@ l1
SequenceCases[#, {a__, b_} :> Sequence @@ {{a}, b}] & /@ l1


Result:

{{{2015, 5, 6}, 13692}, {{2015, 5, 7}, 13715}, {{2015, 5, 10},
13274}, {{2015, 5, 11}, 13581}, {{2015, 5, 12}, 13609}}

b = Map[List[Flatten@Partition[#, 3], Last[#]] &, l1]