3
$\begingroup$

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.

$\endgroup$
4
$\begingroup$

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}] &
$\endgroup$
2
$\begingroup$
MapThread[Map[Function[pair, Append[pair, #2]], #1] &, {l1, l2}]
$\endgroup$
2
$\begingroup$
Flatten /@ Thread[#] & /@ Transpose[{l1, l2}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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