4

I have two lists. E.g.

l1 = {{{t1, d11}, {t2, d12}, {t3, d13}}, 
      {{t1, d21}, {t2, d22}, {t3, d23}}, 
      {{t1, d31}, {t2, d32}, {t3, d33}}, 
      {{t1, d41}, {t2, d42}, {t3, d43}}};

l2 = {p1, p2, p3, p4};

I would like to generate a list like res.

l22 = Table[l2[[i]], {i, 1, Length[l2]}, {Length[l1]}];

res = Table[Riffle[l1[[i, j]], l22[[i]], 3], {i, 1, 4}, {j, 1, 3}]
{{{t1, d11, p1}, {t2, d12, p1}, {t3, d13, p1}}, 
{{t1, d21, p2}, {t2, d22, p2}, {t3, d23, p2}},
{{t1, d31, p3}, {t2, d32, p3}, {t3, d33, p3}},
{{t1, d41, p4}, {t2, d42, p4}, {t3, d43, p4}}} 

It would be nice to have a code in one step and without counting the length of the list. I have seen similar manipulations with Append or Join, but I could not combined with mapping to get the right structure.

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
Vica
  • 391
  • 1
  • 11

3 Answers3

6

I feel like it is a duplicate, but I can't find it, so here's one way:

MapThread[Flatten /@ Thread[{##}] &, {l1, l2}]

or another:

MapThread[# /. {x_, y_} :> {x, y, #2} &, {l1, l2}]
{{{t1, d11, p1}, {t2, d12, p1}, {t3, d13, p1}}, 
{{t1, d21, p2}, {t2, d22, p2}, {t3, d23, p2}}, 
{{t1, d31, p3}, {t2, d32, p3}, {t3, d33, p3}}, 
{{t1, d41, p4}, {t2, d42, p4}, {t3, d43, p4}}}

And ugly one:

Riffle[Transpose[Flatten /@ l1], {l2}, {3, -1, 3}]//Transpose//ArrayReshape[#, {4, 3, 3}] &
Kuba
  • 136,707
  • 13
  • 279
  • 740
3
Flatten /@ Thread[#] & /@ Transpose[{l1, l2}]
Cameron Murray
  • 921
  • 7
  • 16
2
MapThread[Map[Function[pair, Append[pair, #2]], #1] &, {l1, l2}]
Chris Degnen
  • 30,927
  • 2
  • 54
  • 108