2

I have a list with three levels.

list = {{{7, 5, 8}, {4, 8, 9}, {7, 0, 1}, {3, 0, 4}, {5, 1, 2}}};

And I want to put in a list {e,x,y} at the end of every element.

Append[Riffle[#, {{e, x, y}}] & /@ list, {e, x, y}]

Gives:

{{{7, 5, 8}, {e, x, y}, {4, 8, 9}, {e, x, y}, {7, 0, 1}, {e, x, 
   y}, {3, 0, 4}, {e, x, y}, {5, 1, 2}}, {e, x, y}}
  1. There is that {e,x,y} missing at the end.
  2. How do I group every two elements together to get:
{{{7, 5, 8, e, x, y}, {4, 8, 9, e, x, y}, {7, 0, 1, e, x, 
   y}, {3, 0, 4, e, x, y}, {5, 1, 2, e, x, y}}}

Is there is function to do it in one line?

R Walser
  • 149
  • 5

3 Answers3

1
Map[Join[#, {e, x, y}] &, list, {2}]
{{{7, 5, 8, e, x, y}, {4, 8, 9, e, x, y}, {7, 0, 1, e, x, y}, 
{3, 0, 4, e, x, y}, {5, 1, 2, e, x, y}}}

Also

list /. {a__Integer} :> {a, e, x, y}

Map[Flatten[Riffle[{#}, {{e, x, y}}]] &, list, {2}]

Map[PadRight[#, Length@# + 3, {e, x, y}] &, list, {2}]

List @ ArrayPad[First@list, {{0}, {0, 3}}, {{e, x, y}}]

Flatten[Outer[Join, First@list, {{e, x, y}}, 1], {2}]

List @ (Join @@@ Tuples[{First@list, {{e, x, y}}}])

List[Join @@@ Thread[{First@list, {e, x, y}}, List, 1]]

kglr
  • 394,356
  • 18
  • 477
  • 896
0

Try

list={{{7,5,8},{4,8,9},{7,0,1},{3,0,4},{5,1,2}}};
{Join[#,{e,x,y}]&/@list[[1]]}

which returns

{{{7,5,8,e,x,y},{4,8,9,e,x,y},{7,0,1,e,x,y},{3,0,4,e,x,y},{5,1,2,e,x,y}}}
Bill
  • 12,001
  • 12
  • 13
0

Use ArrayFlatten:

m = {{7, 5, 8}, {4, 8, 9}, {7, 0, 1}, {3, 0, 4}, {5, 1, 2}};

ArrayFlatten[{{m, e, x, y}}]

{{7, 5, 8, e, x, y},
 {4, 8, 9, e, x, y},
 {7, 0, 1, e, x, y},
 {3, 0, 4, e, x, y},
 {5, 1, 2, e, x, y}}

There is an extra List level in both your input and output examples that I dropped as it only obfuscates this operation. This extra level can be easily added after if needed.

{ ArrayFlatten[{Join[list, {e, x, y}]}] }
{{{7, 5, 8, e, x, y}, {4, 8, 9, e, x, y},
 {7, 0, 1, e, x, y}, {3, 0, 4, e, x, y}, {5, 1, 2, e, x, y}}}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371