8
$\begingroup$

Here's the deal: I have a table that has the form

 list = {{A,{a,b,c}},{B,{d,e,f}},{C,{g,h,i,j}}} 

and so on, where the innermost lists can have an arbitary number of elements that differs from list to list, and I'd like it to look like

{{A,a},{A,b},{A,c},{B,d},{B,e},{B,f},{C,g},{C,h},{C,i},{C,j}} 

and so on. How do I do this?

$\endgroup$
6
  • 11
    $\begingroup$ Join @@ (Thread /@ list) $\endgroup$ Commented Nov 24, 2015 at 15:21
  • 1
    $\begingroup$ My first answer was the following monstrosity: Flatten[Inner[Outer[##] /. x_[y_] :> {x, y} &, Sequence @@ Transpose[l], List], 1] $\endgroup$ Commented Nov 24, 2015 at 15:27
  • $\begingroup$ @PatrickStevens How nice! :) $\endgroup$ Commented Nov 24, 2015 at 15:30
  • 1
    $\begingroup$ @belisariushassettled I am definitely of the "add more stuff until it works" school of programming. $\endgroup$ Commented Nov 24, 2015 at 15:31
  • 3
    $\begingroup$ @PatrickStevens The Mathematica environment somehow encourages that. It is unbelievable how much one can entangle a simple problem by following a line of thought instead of giving it a break and think again! $\endgroup$ Commented Nov 24, 2015 at 15:34

2 Answers 2

6
$\begingroup$

Here's a simple one-liner:

Apply[Join]@*Map[Thread]@list

(* {{A, a}, {A, b}, {A, c}, {B, d}, {B, e}, {B, f}, {C, g}, {C, h}, {C, i}, {C, j}} *)
$\endgroup$
1
  • 1
    $\begingroup$ Love the mix of operator forms and composition. $\endgroup$
    – march
    Commented Nov 24, 2015 at 16:52
9
$\begingroup$

Since V10.0 you can use the following clear expression

Catenate[Thread /@ list]
(* {{A, a}, {A, b}, {A, c}, {B, d}, {B, e}, {B, f}, {C, g}, {C, h}, {C, 
  i}, {C, j}} *)
$\endgroup$
2
  • $\begingroup$ I checked that timings of Catenate[...] and Faltten[...,1] are almost the same. $\endgroup$
    – ybeltukov
    Commented Nov 24, 2015 at 16:17
  • $\begingroup$ +1 I always forget about Catenate! $\endgroup$
    – Pillsy
    Commented Nov 24, 2015 at 17:15

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.