6

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.

Kuba
  • 136,707
  • 13
  • 279
  • 740

7 Answers7

8
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
eldo
  • 67,911
  • 5
  • 60
  • 168
5

and a classic:

{{#, #2, #3}, #4} & @@@ l1
Kuba
  • 136,707
  • 13
  • 279
  • 740
3
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}}

user1066
  • 17,923
  • 3
  • 31
  • 49
3
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 *)

eldo
  • 67,911
  • 5
  • 60
  • 168
3
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}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
3
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}}

Syed
  • 52,495
  • 4
  • 30
  • 85
2
b = Map[List[Flatten@Partition[#, 3], Last[#]] &, l1] 
Alucard
  • 2,639
  • 13
  • 22