6
$\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$

4 Answers 4

11
$\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$
2
  • $\begingroup$ oh this one is smooth $\endgroup$
    – alex
    May 15 at 7:05
  • $\begingroup$ Flatten[Thread /@ a, 1] this could also be a good alternative. $\endgroup$
    – alex
    May 15 at 7:09
6
$\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$
6
$\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, 2021 at 12:08
  • $\begingroup$ Thank you @LukasLang.; excellent point. Added your suggestion. $\endgroup$
    – kglr
    Jul 12, 2021 at 12:57
4
$\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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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