4
$\begingroup$

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.

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

4 Answers 4

6
$\begingroup$
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
$\endgroup$
1
  • $\begingroup$ Thanks a lot! Both work. The second answer with 'Replace' is fantastic. I understand it since it's more close to my level! $\endgroup$ Aug 8, 2017 at 19:55
4
$\begingroup$

and a classic:

{{#, #2, #3}, #4} & @@@ l1
$\endgroup$
2
$\begingroup$
b = Map[List[Flatten@Partition[#, 3], Last[#]] &, l1] 
$\endgroup$
1
$\begingroup$
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}}

$\endgroup$

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.