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?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityI 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}}
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.
You can do Map[{Most[#], Last[#]} &, list]
to produce the desired output.
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}} *)
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.