4
$\begingroup$

I have three lists.

x = {a,b,c,d}
y = {A,B,C}
z = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}

and I wish to construct the following list out of these three lists

{{a,A,1},{a,B,2},{a,C,3},{b,A,4},{b,B,5},{b,C,6},{c,A,7},{c,B,8},{c,C,9},{d,A,10},{d,B,11},{d,C,12}}

In the above list, every sublist or z is matched to an element in x and every item within a sublist in z is matched with an element in y.

How can I achieve this?

$\endgroup$

5 Answers 5

5
$\begingroup$
Transpose[{## & @@ Transpose@Tuples[{x, y}], Flatten@z}]
(* {{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6},
    {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}} *)

or

Flatten /@ Thread[{Tuples[{x, y}], Flatten@z}]
(* {{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6},
    {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}} *)

or

MapThread[Append, {Tuples[{x, y}], Flatten[z]}]
(* {{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6},
    {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}} *)
$\endgroup$
3
$\begingroup$
Flatten[Table[{x[[i]], y[[j]], z[[i, j]]}, {i, 1, Length[x]}, {j, 1, Length[y]}], 1]

{{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6}, {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}}

$\endgroup$
3
$\begingroup$
Thread /@ Thread[{x, {y, y, y, y}, z}] // Flatten[#, 1] &

returns

{{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6}, {c,A, 7},
 {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}}
$\endgroup$
1
$\begingroup$
{Tuples[{x,y}],Flatten[z]}\[Transpose]/.{{x_,y_},r_}:>{x,y,r}
$\endgroup$
1
$\begingroup$
Riffle[Flatten@Outer[List, x, y], Flatten@z, {3, -1, 3}] ~Partition~ 3
{{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6}, {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}}
$\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.