I have data that, when imported to my notebook, is shown in the form:
list = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}
I want to transform this into:
list = {{{1,2},3},{{4,5},6},{{7,8},9},{{10,11},12}}
How can I do this?
I have data that, when imported to my notebook, is shown in the form:
list = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}
I want to transform this into:
list = {{{1,2},3},{{4,5},6},{{7,8},9},{{10,11},12}}
How can I do this?
Map
With no Map
s.
list = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
Transpose@{list[[;; , ;; 2]], list[[;; , 3]]}
{{{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9}, {{10, 11}, 12}}
Apply
Not technically Map
, but still iterating.
{{#1, #2}, #3} & @@@ list
{{{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9}, {{10, 11}, 12}}
Another way
list /. {x_, y_, z_} -> {{x, y}, z}
{{{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9}, {{10, 11}, 12}}
You can do Map[{Most[#], Last[#]} &, list]
to produce the desired output.
also you can do
lst = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}
{#[[;; -2]], #[[-1]]} & /@ lst
Also possible (if you like to view things as matrices)
a = Map[List, lst[[All, {1, -2}]]]
b = lst[[All, -1]]
MapThread[Append, {a, b}]
8 more different 6 more ways could be possible.
Using SequenceCases:
SequenceCases[list, {x_}:>{Most@x, Last@x}]
A rule-based approach:
list = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
list /. {x__?NumericQ, y_?NumericQ} :> {{x}, y}
A simple Table
-based approach:
Table[{list[[kk, 1 ;; 2]], list[[kk, 3]]}, {kk, 1, Length@list}]
BlockMap[Join,Riffle[list[[All,;;2]],list[[All,3]]],{2}]
(* {{{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9}, {{10, 11}, 12}} *)
In addition
Fold[List,#]&/@list
(* {{{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9}, {{10, 11}, 12}} *)
Also
MapThread[{{#1,#2},#3}&,Transpose[list]]
(* {{{1,2},3},{{4,5},6},{{7,8},9},{{10,11},12}} *)
You can use Partition
. All of the following work:
Map[{Flatten[Partition[#, 2]], #[[-1]]} &, list]
Map[{Flatten[Partition[#, 2]], #[[3]]} &, list]
Map[{First[Partition[#, 2]], #[[-1]]} &, list]
Map[{First[Partition[#, 2]], #[[3]]} &, list]
Map[{First[Partition[#, 2]], Last[#]} &, list]
The well known IA told me, with the exact question as prompt :
In[1]:= list = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}
Out[1]= {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}
In[2]:= transformedList = Map[{Take[#, 2], Last[#]} &, list]
Out[2]= {{{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9}, {{10, 11}, 12}}
And it works. I never touched mathics before. It's not (so much) ironic but to remember that new fact.
list = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
With Comap
(new in 14.0)
Comap[{Most, Last}] /@ list
{{{1, 2}, {3}}, {{4, 5}, {6}}, {{7, 8}, {9}}, {{10, 11}, {12}}}
With TakeList
(new in 11.2)
TakeList[#, {2, 1}] & /@ list
{{{1, 2}, {3}}, {{4, 5}, {6}}, {{7, 8}, {9}}, {{10, 11}, {12}}}
With Query
(new in 10.0)
Query[All, {Most, Last}] @ list
{{{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9}, {{10, 11}, 12}}