Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
    
related: 13748 – Kuba May 7 '14 at 8:34
    
cross posted on Wolfram Community – Kuba Apr 29 '15 at 20:05
up vote 3 down vote accepted

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}] &
share|improve this answer
MapThread[Map[Function[pair, Append[pair, #2]], #1] &, {l1, l2}]
share|improve this answer
Flatten /@ Thread[#] & /@ Transpose[{l1, l2}]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.