5
$\begingroup$

I have a very long list from which I will display part of it as,

a={{1, {3, 5, 8, 9}}, {2, {4, 6}}, {6, {1}}, {10, {1, 3, 5, 6, 7, 8}}};

For plotting purposes, I would like to rewrite the list in the following form

a = {{1, 3}, {1, 5}, {1, 8}, {1, 9}, {2, 4}, {2, 6}, {6, 1}, {10, 
1}, {10, 3}, {10, 5}, {10, 6}, {10, 7}, {10, 8}} ; ListPlot[a];

Since the actual list is extremely long, I appreciate it if you can help me in doing this. Please keep in mind that the first number is associated with one or more other numbers.

Thanks in advance.

$\endgroup$
8
$\begingroup$

Using Join and Thread:

Join @@ Thread /@ a
(* {{1, 3}, {1, 5}, {1, 8}, {1, 9}, {2, 4}, {2, 6}, {6, 1}, {10, 1}, {10, 3}, {10, 5}, {10, 6}, {10, 7}, {10, 8}} *)
$\endgroup$
5
$\begingroup$
Map[Splice@*Thread] @ a
{{1, 3}, {1, 5}, {1, 8}, {1, 9}, {2, 4}, {2, 6}, {6, 1}, {10, 1}, 
 {10, 3}, {10, 5}, {10, 6}, {10, 7}, {10, 8}}

Also

Splice @* Thread /@ a  (* thanks: LukasLang *)
{{1, 3}, {1, 5}, {1, 8}, {1, 9}, {2, 4}, {2, 6}, {6, 1}, {10, 1}, 
 {10, 3}, {10, 5}, {10, 6}, {10, 7}, {10, 8}}

For versions older than 12.0 replace Splice with Apply[Sequence].

$\endgroup$
2
  • 1
    $\begingroup$ Thanks to the precedence of @*, you could also use Splice@*Thread /@ a $\endgroup$
    – Lukas Lang
    Jul 12 at 12:08
  • $\begingroup$ Thank you @LukasLang.; excellent point. Added your suggestion. $\endgroup$
    – kglr
    Jul 12 at 12:57
4
$\begingroup$

I am sure there are at least 10 ways to do this in Mathematica. One that comes to mind now is

a={{1, {3, 5, 8, 9}}, {2, {4, 6}}, {6, {1}}, {10, {1, 3, 5, 6, 7, 8}}};
Flatten[Cases[a, {x_, {y___}} :> ({x, #} & /@ {y})], 1]

gives

{{1, 3}, {1, 5}, {1, 8}, {1, 9}, {2, 4}, {2, 6}, {6, 1}, {10, 1}, {10,
   3}, {10, 5}, {10, 6}, {10, 7}, {10, 8}}
$\endgroup$
3
$\begingroup$
a//Table[Splice@Distribute[#[[i]],List], {i,1,Length@#}]& 

(* {{1, 3}, {1, 5}, {1, 8}, {1, 9}, {2, 4}, {2, 6}, {6, 1}, {10, 1}, {10,   3}, {10, 5}, {10, 6}, {10, 7}, {10, 8}}  *)
$\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.