jeff
(Jeff Burns)
November 20, 2016, 1:40am
1
This code gives the result I need, but there must be a better way. Any ideas?
l1 = {1, 2, 3}
l2 = {{a1, b1, c1, d1}, {a2, b2, c2}, {a2, b2, c2}}
Flatten[Module[{t},
MapThread[(#2 /. t -> #1) &,
{l1, Map[{t, #} &, l2, {2}]}
]
], 1
]
The result is:
{{1, a1}, {1, b1}, {1, c1}, {1, d1}, {2, a2}, {2, b2}, {2, c2}, {3,
a2}, {3, b2}, {3, c2}}
sghuisman
(Sander Huisman)
November 20, 2016, 4:26am
2
Many many possibilities, I give you two other ways:
Join @@ MapThread[Thread[{#1, #2}] &, {l1, l2}]
Transpose[{Join @@ MapThread[ConstantArray, {l1, Length /@ l2}], Join @@ l2}]
Depending on the types of data (all numerical, symbolic, mixed) one method will be faster than the other…
NB. Note that Flatten[…,1] is the same as Join @@ … , but the latter is generally faster (or in the worst case, equal). I’m not sure how it compares to Catenate @ … though, I have a feeling it is a more ‘higher-level’ function, and probably slower…
vaungureanu
(Valeriu Ungureanu)
November 20, 2016, 8:39am
3
Other possibilities:
Flatten[Table[{l1[[i]], l2[[i, j]]}, {i, Length[l1]}, {j,Length[l2[[i]]]}], 1]
Table[{l1[[i]], l2[[i, j]]}, {i, Length[l1]}, {j,Length[l2[[i]]]}] // Catenate
Flatten[Diagonal@Outer[List, l1, l2], 1]
Catenate@Diagonal@Outer[List, l1, l2]
szhorvat
(Szabolcs Horvát)
November 20, 2016, 11:49am
4
I like
Catenate@MapThread[Thread@*List, {l1, l2}]
jeff
(Jeff Burns)
November 20, 2016, 7:18pm
5
This is the fastest, but I am not sure how this part work “Thread@*List”. Can someone help me break it down?
szhorvat
(Szabolcs Horvát)
November 20, 2016, 9:24pm
6
@* is short for Composition. Thread@*List does the same as Sander’s Thread[{#1,#2}].
jeff
(Jeff Burns)
November 23, 2016, 1:35am
7
Thanks. That clears it up. I tried searching for @* in the help, but it does not return any results. Knowing the name of the command helps.