2
$\begingroup$

I am trying to do something like this:

If l1, l2, p1, p2, q1, q2 and q3 are lists then I want to know how I can obtain the following list:

in1 = {l1, l2}
in2 = {{p1,p2},{q1,q2,q3}}
output = {{l1,p1},{l1,p2},{l2,q1},{l2,q2},{l2,q3}}

I am doing it with the following code:

step1[l1_, l2_] := Table[l1, {Length@l2}]

step2[l1_, l2_] := step1 @@@ (Transpose@{l1, l2})

final[l1_, l2_] :=  Transpose@{Flatten[#, 1] &@step2[l1, l2], Flatten[#, 1] &@l2}

But I want to know if there are other options.

$\endgroup$

1 Answer 1

3
$\begingroup$
in1 = {l1, l2};
in2 = {{p1, p2}, {q1, q2, q3}};

Join @@ Thread /@ Thread[{in1, in2}] 
Inner[List, in1, in2, Join @@ Thread /@ {##} &]
Inner[Thread @ {##} &, in1, in2, Join]
Flatten[Tuples /@ Transpose[{List /@ in1, in2}], 1]
Flatten[MapThread[Tuples[{{#1}, #2}] &, {in1, in2}], 1]
Flatten[MapThread[Thread[{##}] &, {in1, in2}], 1] (* thanks:  aardvark2012 *)
MapThread[Outer[List, {#1}, #2] &, {in1, in2}]~Flatten~2 (* thanks:  Jason B. *)

all give

{{l1, p1}, {l1, p2}, {l2, q1}, {l2, q2}, {l2, q3}}

$\endgroup$
5
  • 1
    $\begingroup$ similar: MapThread[Outer[List, {#1}, #2] &, {in1, in2}]~Flatten~2 $\endgroup$
    – Jason B.
    Commented Sep 12, 2017 at 20:28
  • $\begingroup$ @JasonB., nice; i added a variant with Tuples. $\endgroup$
    – kglr
    Commented Sep 12, 2017 at 20:43
  • $\begingroup$ Also Flatten[MapThread[Thread[{#1, #2}] &, {in1, in2}], 1] $\endgroup$ Commented Sep 12, 2017 at 22:26
  • $\begingroup$ @aardvark2012, thank you. I added your suggestion. $\endgroup$
    – kglr
    Commented Sep 12, 2017 at 23:30
  • 1
    $\begingroup$ Maybe I misunderstood the question but if l2, p1, q3 etc. have arbitrary lists assigned to them only a couple of these methods work. $\endgroup$
    – Mr.Wizard
    Commented Sep 13, 2017 at 0:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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