8

What is the best way to do this?

in:

{a, b, c}
{d, {e, f}, g}

out:

{{a, d}, {b, e}, {b, f}, {c, g}}

If[Length[#[[2]]] > 0, Transpose[{Table[#[[1]], {x, Length[#[[2]]]}], #[[2]]}], #] 
& /@ Partition[Riffle[{a, b, c}, {d, {e, f}, g}], 2]

seems a bit longwinded.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
martin
  • 8,678
  • 4
  • 23
  • 70
  • 2
    Just for fun, not good for numbers :) : Flatten[MapThread[ArcTan, {{a, b, c}, {d, {e, f}, g}}]] /. ArcTan -> List. – Kuba Feb 20 '15 at 19:27
  • @Kuba You jogged a memory. I think this question is a duplicate. I remember writing this before: Quiet@Re[{a, b, c}, {d, {e, f}, g}] /. Re -> List. Let me see if I can find it. – Mr.Wizard Feb 20 '15 at 19:32
  • Related: (17400), and my answer with Re: (28693). Sadly no votes. :'-( – Mr.Wizard Feb 20 '15 at 19:34
  • This question is almost a duplicate of 17400 linked above, but flat output is desired. I don't know if that is enough to keep this open or not. I'll let the community votes decide. – Mr.Wizard Feb 20 '15 at 19:35

6 Answers6

10
l1 = {a, b, c};
l2 = {d, {e, f}, g};

Partition[Flatten[Thread /@ Thread[{l1, l2}]], 2]

{{a, d}, {b, e}, {b, f}, {c, g}}

or

(## & @@ Thread @ #) & /@ Thread[{l1, l2}]

{{a, d}, {b, e}, {b, f}, {c, g}}

kglr
  • 394,356
  • 18
  • 477
  • 896
8

Using undocumented Function syntax, Listable, and v10 Composition syntax:

fn1 = #[[2, 1]] & @* Reap @* Function[, Sow[{##}], Listable];

fn1[{a, b, c}, {d, {e, f}, g}]
{{a, d}, {b, e}, {b, f}, {c, g}}

This works at deeper levels as well:

fn1[{a, b, c}, {d, {{e1, e2}, f}, g}]
{{a, d}, {b, e1}, {b, e2}, {b, f}, {c, g}}

Another method without the undocumented functionality:

With[{h = Unique["h", Listable]},
  fn2 = Cases[h[##], h[e__] :> {e}, -1] &
]

Test:

fn2[{a, b, c}, {d, {{e1, e2}, f}, g}]
{{a, d}, {b, e1}, {b, e2}, {b, f}, {c, g}}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
3

Using ReplaceAll with Splice (since V. 13.1)

l1 = {a, b, c};
l2 = {d, {e, f}, g};

Transpose[{l1, l2}] /. {a_, {b_, c_}} :> Splice[{{a, b}, {a, c}}]

{{a, d}, {b, e}, {b, f}, {c, g}}

eldo
  • 67,911
  • 5
  • 60
  • 168
3

Update

MapThread[Thread@*List,{l1,l2}]//FlattenAt[2]

(* {{a,d},{b,e},{b,f},{c,g}} *)

Or

Level[MapThread[Thread@*List,{l1,l2}],{-2}]

(* {{a,d},{b,e},{b,f},{c,g}} *)


Original Answer

MapThread[Thread[Distribute[{##}]]&,{l1,l2}]//FlattenAt[2]

(* {{a,d},{b,e},{b,f},{c,g}} *)

Or

Level[MapThread[Thread[Distribute[{##}]]&,{l1,l2}],{-2}]

(* {{a,d},{b,e},{b,f},{c,g}} *)

user1066
  • 17,923
  • 3
  • 31
  • 49
3

One way:

ff = Flatten[#, 1] &; 
ff@MapThread[Function[{u, v}, {u, #} & /@ ff[{v}]], {{a, b, c}, {x, {y, u}, z}}]

(* {{a, x}, {b, y}, {b, u}, {c, z}}*)
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
3
l1 = {a, b, c};
l2 = {d, {e, f}, g};    
Level[Thread[{#, #2}] & @@@ Transpose[{l1, l2}], {-2}]
(*{{a, d}, {b, e}, {b, f}, {c, g}}*)
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78